public void Log <TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { var nLogLogLevel = ConvertLogLevel(logLevel); if (!IsEnabled(nLogLogLevel)) { return; } if (formatter == null) { throw new ArgumentNullException(nameof(formatter)); } var messageParameters = NLogMessageParameterList.TryParse(_options.CaptureMessageTemplates ? state as IReadOnlyList <KeyValuePair <string, object> > : null); LogEventInfo eventInfo = TryParseLogEventInfo(nLogLogLevel, messageParameters) ?? CreateLogEventInfo(nLogLogLevel, formatter(state, exception), messageParameters); if (exception != null) { eventInfo.Exception = exception; } CaptureEventId(eventInfo, eventId); if (messageParameters == null) { CaptureMessageProperties(eventInfo, state); } _logger.Log(typeof(Microsoft.Extensions.Logging.ILogger), eventInfo); }
private LogEventInfo CreateLogEventInfo <TState>(LogLevel nLogLogLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { if (_options.CaptureMessageProperties && state is IReadOnlyList <KeyValuePair <string, object> > messagePropertyList) { if (_options.CaptureMessageTemplates) { var messageParameters = NLogMessageParameterList.TryParse(messagePropertyList); if (messageParameters.Count == 0) { var logEvent = LogEventInfo.Create(nLogLogLevel, _logger.Name, formatter(state, exception)); CaptureEventIdProperties(logEvent, eventId); return(logEvent); } else { var logEvent = TryParseMessageTemplate(nLogLogLevel, messagePropertyList, messageParameters) ?? CaptureMessageTemplate(nLogLogLevel, formatter(state, exception), messagePropertyList, messageParameters); CaptureEventIdProperties(logEvent, eventId); return(logEvent); } } else { var logEvent = LogEventInfo.Create(nLogLogLevel, _logger.Name, formatter(state, exception)); CaptureMessagePropertiesList(logEvent, messagePropertyList); CaptureEventIdProperties(logEvent, eventId); return(logEvent); } } else { var logEvent = LogEventInfo.Create(nLogLogLevel, _logger.Name, formatter(state, exception)); if (_options.CaptureMessageProperties) { if (state is IEnumerable <KeyValuePair <string, object> > messageProperties) { CaptureMessageProperties(logEvent, messageProperties); } CaptureEventIdProperties(logEvent, eventId); } return(logEvent); } }
/// <summary> /// Convert IReadOnlyList to <see cref="NLogMessageParameterList"/> /// </summary> /// <param name="messageProperties"></param> /// <returns></returns> private NLogMessageParameterList TryParseMessageParameterList(IReadOnlyList <KeyValuePair <string, object> > messageProperties) { return((messageProperties != null && _options.CaptureMessageTemplates) ? NLogMessageParameterList.TryParse(messageProperties) : null); }