Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NLog - Save ${message} in multiple database columns

Tags:

c#

nlog

I'd like to save the logged message ${message} in several columns in a database, as shown on the following example:

My logger messages will follow the path User|Action, e.g:

logger.Info("John Doe|Logged in application"}  
logger.Info("Mike Doe|Deleted a file"}

Now I'd like to save User in a column in my database, e.g logsTable.user, and Action in another column, e.g logsTable.action.

Is there any way to parse the ${message} with a regex or some other rules (to separate messages according to a specific character, in my example it's a "|") to save into parameters (in my case, i'd like the first part of the message to go in @user parameter and the second part in @action parameter)?

like image 344
Otiel Avatar asked Aug 18 '26 08:08

Otiel


1 Answers

According to NLog documentation it shouldn't be too complicated to add your own properties to a log event. Then you could do an extension method on the correct NLog interface and write something like this (uncompiled):

public void LogSomething(this ILog logger, string username, string message)
{
  LogEventInfo myEvent = new LogEventInfo(LogLevel.Debug, "", message);
  myEvent.LoggerName = logger.Name;
  myEvent.Properties.Add("User", username);
  logger.Log(myEvent);
}

Now you should be able to refer to ${event-context:item=User}

like image 191
flq Avatar answered Aug 20 '26 23:08

flq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!