Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PowerShell

Parse Log4Net log files with PowerShell

0.00/5 (No votes)
15 Feb 2013CPOL 20K  
PowerShell in general can be used for searching text in files. The same fearture helps to get required debugging info from log files on the production server,

Introduction

Recently, I was needed to debug an issue in a deployed web application on production server in client premises. To get the logs on dev machine, I needed through go their approval systems and then somebody from their used to get me the logs. I cannot install other tools on production server to filter out the logs. There were too many log files to go through. So I have to live with what I have. So PowerShell came to rescue me here.

Background 

PowerShell is task-based command-line shell and scripting language built on top of the .NET Framework. So most of the basic functionality are available for our task at hand.

Using the code 

So the task is parse the text file with regular expression with PowerShell commandline. Here is the sample log file the Log4Net has generated.
C++
2013-02-12 01:31:25 - Trying for user: 986233
2013-02-12 01:31:25 - Failed.
2013-02-12 01:31:41 - Trying for user: : 956318
2013-02-12 01:31:41 - Success.
2013-02-12 01:31:56 - Trying for user: : 468533
2013-02-12 01:31:56 - Success.
2013-02-12 01:32:11 - Trying for user: : 496924
2013-02-12 01:32:11 - Failed. 
2013-02-12 01:32:26 - Trying for user: : 774469
2013-02-12 01:32:26 - Success.
2013-02-12 01:32:41 - Trying for user: : 799631
2013-02-12 01:32:41 - Success.

And now we need to write one or more command line statements to get failed user ids. Here is how I did it.

C++
PS D:\WorkSpace\Apps> [regex]::matches((get-content .\WebLog.txt | out-string ),
 '.*Trying.*\r\n.*Failed.*', "Multiline") | foreach { $_.Groups[0].Value } 

And the result was as expected 

C++
2013-02-12 01:31:25 - Trying for user: 986233
2013-02-12 01:31:25 - Failed.
2013-02-12 01:32:11 - Trying for user: : 496924
2013-02-12 01:32:11 - Failed. 

Points of Interest

We can get matching string easily from Select-String commandlet but It took some time for me to write multiline regular expression in PowerShell.

History

  • 02/15/2013 - v1.0.0 - Initial commit.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)