1

I have a string line from a log:

2020-09-07 14:41:17.268 +01:00 [Information] Hello, Serilog!

I would like to pull out the word Information from the string, however, this will change as it could be debug, or any other known logging level.

I would also like the message, which is one space after the ] which in this case is Hello, Serilog!. This is also subject to change but it wont be any longer than the existing message.

The string is coming from a StringReader

 using (StringReader reader = new StringReader(message.ToString())) // message from StringWriter
{
    var readText = reader.ReadLine();
    Console.WriteLine(readText);
}

What is the best way to do this?

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91
user1574598
  • 3,771
  • 7
  • 44
  • 67
  • 1
    Since the string will always contains the brackets `[]` you can split the string on the last one `]` and get every thing after as the message and everything before until the `[` as the log type. or you can use Regex. – HMZ Sep 07 '20 at 14:01
  • Thanks im just looking at regex now – user1574598 Sep 07 '20 at 14:02
  • If you're trying to parse logs, it might be easier to output the logs as JSON, if that's an option for you. – ESG Sep 07 '20 at 23:00

2 Answers2

1

You can use regular expression as follows:

var regex = new Regex("\\[([^\\]]+)\\]");
var match = regex.Match(readText);
if (match.Success)
{
    var value = match.Groups[1].Value;
    // value == "Information" or whatever between [ and ]
}
else
{
    // Handle pattern not matching
}
Sherif Elmetainy
  • 4,034
  • 1
  • 13
  • 22
1

Using Regex will output Information: Hello, Serilog!

string type;
string message;

string text = "2020-09-07 14:41:17.268 +01:00 [Information] Hello, Serilog!";
string pattern = "\\[(.*?)\\]";
var match = Regex.Match(text, pattern);
if (match.Success)
{
    type = match.Groups[1].Value;
    message = text.Substring(match.Groups[1].Index + match.Groups[1].Length + 1);
    Console.WriteLine(type + ": " + message);
}            
Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91