开发者

NLog - Save ${message} in multiple database columns

开发者 https://www.devze.com 2023-03-31 16:06 出处:网络
I\'d like to save the logged message ${message} in several columns in a database, as shown on the following example:

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)?


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}

0

精彩评论

暂无评论...
验证码 换一张
取 消