운영체제/윈도우

[PowerShell] 로그파일 실시간 출력

IT 기술자 2024. 1. 19. 11:00

0. 개요

윈도에서도 리눅스와 같은 실시간 로그를 확인하자.  또한 C# 프로그램에서 원하는 파일을 파워쉘을 실행하여 실시간 로그를 확인하자.

 

1. PowerShell에서 로그 확인

리눅스 Bash에서 다음 명령을 실행하면,

tail -f [파일전체경로]

파일의 실시간 로그를 출력한다.

 

이와  같은 기능을 하는 윈도 PowerShell 명령은 다음과 같다.

Get-Content -tail 10 -wait [파일전체경로]

 

log4net을 적용한 프로그램에서 Debug, Info, Warn, Error 상태에 따라 라인 색을 다르게 보여주려 한다면 다음과 같은 명령을 수행한다.

powershell  -Command @'
function Get-LogColor {
    Param([Parameter(Position=0)]
    [String]$LogEntry)

    process {
        if ($LogEntry.Contains(\"DEBUG\")) {Return \"Green\"}
        elseif ($LogEntry.Contains(\"WARN\")) {Return \"Yellow\"}
        elseif ($LogEntry.Contains(\"ERROR\")) {Return \"Red\"}
        else {Return \"White\"}
    }
}
Get-Content -tail 10 -wait [파일전체패스] | ForEach {Write-Host -ForegroundColor (Get-LogColor $_) $_}
'@

 

2. C#에서 로그 확인

C#에서 프로그램에서 컨트롤하기 위해서는 아래와 같은 코드를 실행한다.

readonly string _getLogColorHead = @"function Get-LogColor {
    Param([Parameter(Position=0)]
    [String]$LogEntry)

    process {
        if ($LogEntry.Contains("" DEBUG "")) {Return ""Green""}
        elseif($LogEntry.Contains("" WARN "")) {Return ""Yellow""}
        elseif ($LogEntry.Contains("" ERROR "")) {Return ""Red""}
        else {
            Return ""White""}
    }
}
";

readonly string _getLogColorTail = " | ForEach {Write-Host -ForegroundColor (Get-LogColor $_) $_}";

string DecodeFromUtf8(string utf8String)
{
    // copy the string as UTF-8 bytes.
    byte[] utf8Bytes = new byte[utf8String.Length];
    for (int i = 0; i < utf8String.Length; ++i)
    {
        //Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
        utf8Bytes[i] = (byte)utf8String[i];
    }
    return Encoding.UTF8.GetString(utf8Bytes, 0, utf8Bytes.Length);
}

void ExecuteCommand(string command)
{
    string utf16 = DecodeFromUtf8(command);
    byte[] byteArr = Encoding.Unicode.GetBytes(utf16);
    string base64 = Convert.ToBase64String(byteArr);

    var processStartInfo = new ProcessStartInfo();
    processStartInfo.FileName = "powershell.exe";
    processStartInfo.Arguments = $"-EncodedCommand {base64}";
    processStartInfo.UseShellExecute = false;
    processStartInfo.RedirectStandardOutput = false;
    processStartInfo.RedirectStandardError = true;

    using var process = new Process();
    process.StartInfo = processStartInfo;
    process.Start();
}

ExecuteCommand($"{_getLogColorHead}get - content -tail 100 -wait {[파일전체경로]}{_getLogColorTail}");

 

3. 실행 화면

파워쉘이나 C#에서 실행하면 다음과 같이 로그 레벨에 따라 행의 글자 색이 다르게 표시된다.

 

참고. Base 64 실행 참고

Wiki : PowerShell의 Execution Policy를 우회하는 15가지 방법

https://wiki.wikisecurity.net/tips:powershell_execution_policy%EB%A5%BC_%EC%9A%B0%ED%9A%8C%ED%95%98%EB%8A%94_15%EA%B0%80%EC%A7%80_%EB%B0%A9%EB%B2%95

 

PowerShell의 Execution Policy를 우회하는 15가지 방법 -

* 사업 등 관련 문의: T) 02-322-4688, F) 02-322-4646, E) info@wikisecurity.net PowerShell의 Execution Policy를 우회하는 15가지 방법 개 요 Windows PowerShell은 여러 가지면에서 보안진단자나 시스템운영자 등에게 유용

wiki.wikisecurity.net