public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { var level = logLevel.ToSerilogLevel(); if (!_logger.IsEnabled(level)) { return; } var logger = _logger; string messageTemplate = null; var properties = new List <LogEventProperty>(); if (state is IEnumerable <KeyValuePair <string, object> > structure) { foreach (var property in structure) { if (string.Equals(property.Key, SerilogLoggerProvider._originalFormatPropertyName, StringComparison.OrdinalIgnoreCase) && property.Value is string value) { messageTemplate = value; } else if (property.Key.StartsWith("@", StringComparison.Ordinal)) { if (logger.BindProperty(property.Key.Substring(1), property.Value, destructureObjects: true, out var destructured)) { properties.Add(destructured); } } else { if (logger.BindProperty(property.Key, property.Value, destructureObjects: false, out var bound)) { properties.Add(bound); } } } var stateType = state.GetType(); var stateTypeInfo = stateType.GetTypeInfo(); // Imperfect, but at least eliminates `1 names if (messageTemplate == null && !stateTypeInfo.IsGenericType) { messageTemplate = "{" + stateType.Name + ":l}"; if (logger.BindProperty(stateType.Name, AsLoggableValue(state, formatter), destructureObjects: false, out var stateTypeProperty)) { properties.Add(stateTypeProperty); } } } if (messageTemplate == null) { string propertyName = null; if (state != null) { propertyName = "State"; messageTemplate = "{State:l}"; } else if (formatter != null) { propertyName = "Message"; messageTemplate = "{Message:l}"; } if (propertyName != null && logger.BindProperty(propertyName, AsLoggableValue(state, formatter), false, out var property)) { properties.Add(property); } } if (eventId.Id != 0 || eventId.Name != null) { properties.Add(CreateEventIdProperty(eventId)); } var parsedTemplate = _messageTemplateParser.Parse(messageTemplate ?? ""); var evt = new LogEvent(DateTimeOffset.Now, level, exception, parsedTemplate, properties); logger.Write(evt); }
public void IndexOutOfRangeExceptionBugHasNotRegressed() { var parser = new MessageTemplateParser(); parser.Parse("{,,}"); }
static LogEvent ReadFromJObject(int lineNumber, JObject jObject) { var timestamp = GetRequiredTimestampField(lineNumber, jObject, ClefFields.Timestamp); string messageTemplate; if (!TryGetOptionalField(lineNumber, jObject, ClefFields.MessageTemplate, out messageTemplate)) { string message; if (!TryGetOptionalField(lineNumber, jObject, ClefFields.Message, out message)) { throw new InvalidDataException($"The data on line {lineNumber} does not include the required `{ClefFields.MessageTemplate}` or `{ClefFields.Message}` field."); } messageTemplate = MessageTemplateSyntax.Escape(message); } var level = LogEventLevel.Information; if (TryGetOptionalField(lineNumber, jObject, ClefFields.Level, out string l)) { level = (LogEventLevel)Enum.Parse(typeof(LogEventLevel), l); } Exception exception = null; if (TryGetOptionalField(lineNumber, jObject, ClefFields.Exception, out string ex)) { exception = new TextException(ex); } var unrecognized = jObject.Properties().Where(p => ClefFields.IsUnrecognized(p.Name)); // ReSharper disable once PossibleMultipleEnumeration if (unrecognized.Any()) { // ReSharper disable once PossibleMultipleEnumeration var names = string.Join(", ", unrecognized.Select(p => $"`{p.Name}`")); throw new InvalidDataException($"{names} on line {lineNumber} are unrecognized."); } var parsedTemplate = Parser.Parse(messageTemplate); var renderings = Enumerable.Empty <Rendering>(); if (jObject.TryGetValue(ClefFields.Renderings, out JToken r)) { var renderedByIndex = r as JArray; if (renderedByIndex == null) { throw new InvalidDataException($"The `{ClefFields.Renderings}` value on line {lineNumber} is not an array as expected."); } renderings = parsedTemplate.Tokens .OfType <PropertyToken>() .Where(t => t.Format != null) .Zip(renderedByIndex, (t, rd) => new Rendering(t.PropertyName, t.Format, rd.Value <string>())) .ToArray(); } var properties = jObject .Properties() .Where(f => !ClefFields.All.Contains(f.Name)) .Select(f => { var name = ClefFields.Unescape(f.Name); var renderingsByFormat = renderings.Where(rd => rd.Name == name); return(PropertyFactory.CreateProperty(name, f.Value, renderingsByFormat)); }) .ToList(); string eventId; if (TryGetOptionalField(lineNumber, jObject, ClefFields.EventId, out eventId)) // TODO; should support numeric ids. { properties.Add(new LogEventProperty("@i", new ScalarValue(eventId))); } return(new LogEvent(timestamp, level, exception, parsedTemplate, properties)); }
public CaptureSagaStateBehavior() { var templateParser = new MessageTemplateParser(); messageTemplate = templateParser.Parse("Saga execution '{SagaType}' '{SagaId}'."); }
public void Emit(LogEvent logEvent) { var template = _parser.Parse(logEvent.MessageTemplate.ToString()); var a = ""; }
static LogIncomingMessageBehavior() { var templateParser = new MessageTemplateParser(); messageTemplate = templateParser.Parse("Receive message {IncomingMessageType} {IncomingMessageId}."); }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { var level = ConvertLevel(logLevel); if (!_logger.IsEnabled(level)) { return; } var logger = _logger; string messageTemplate = null; var properties = new List <LogEventProperty>(); var structure = state as IEnumerable <KeyValuePair <string, object> >; if (structure != null) { foreach (var property in structure) { if (property.Key == SerilogLoggerProvider.OriginalFormatPropertyName && property.Value is string) { messageTemplate = (string)property.Value; } else if (property.Key.StartsWith("@")) { LogEventProperty destructured; if (logger.BindProperty(property.Key.Substring(1), property.Value, true, out destructured)) { properties.Add(destructured); } } else { LogEventProperty bound; if (logger.BindProperty(property.Key, property.Value, false, out bound)) { properties.Add(bound); } } } var stateType = state.GetType(); var stateTypeInfo = stateType.GetTypeInfo(); // Imperfect, but at least eliminates `1 names if (messageTemplate == null && !stateTypeInfo.IsGenericType) { messageTemplate = "{" + stateType.Name + ":l}"; LogEventProperty stateTypeProperty; if (logger.BindProperty(stateType.Name, AsLoggableValue(state, formatter), false, out stateTypeProperty)) { properties.Add(stateTypeProperty); } } } if (messageTemplate == null) { var propertyName = state != null ? "State" : (formatter != null ? "Message" : null); if (propertyName != null) { messageTemplate = $"{{{propertyName}:l}}"; LogEventProperty property; if (logger.BindProperty(propertyName, AsLoggableValue(state, formatter), false, out property)) { properties.Add(property); } } } if (eventId.Id != 0 || eventId.Name != null) { properties.Add(CreateEventIdProperty(eventId)); } var parsedTemplate = _messageTemplateParser.Parse(messageTemplate ?? ""); var evt = new LogEvent(DateTimeOffset.Now, level, exception, parsedTemplate, properties); logger.Write(evt); }
public async Task <IActionResult> Post([FromBody] dynamic request, string logger = "") { try { var columnOptions = new ColumnOptions { AdditionalColumns = new Collection <SqlColumn> { new SqlColumn { ColumnName = "JobId", PropertyName = "JobId", DataType = SqlDbType.UniqueIdentifier }, new SqlColumn { ColumnName = "AutomationId", PropertyName = "AutomationId", DataType = SqlDbType.UniqueIdentifier }, new SqlColumn { ColumnName = "AgentId", PropertyName = "AgentId", DataType = SqlDbType.UniqueIdentifier }, new SqlColumn { ColumnName = "MachineName", PropertyName = "MachineName", DataType = SqlDbType.NVarChar }, new SqlColumn { ColumnName = "AgentName", PropertyName = "AgentName", DataType = SqlDbType.NVarChar }, new SqlColumn { ColumnName = "AutomationName", PropertyName = "AutomationName", DataType = SqlDbType.NVarChar }, new SqlColumn { ColumnName = "Id", PropertyName = "Id", DataType = SqlDbType.UniqueIdentifier }, new SqlColumn { ColumnName = "AutomationLogTimeStamp", PropertyName = "AutomationLogTimeStamp", DataType = SqlDbType.DateTime2 }, new SqlColumn { ColumnName = "CreatedOn", PropertyName = "CreatedOn", DataType = SqlDbType.DateTime2 }, new SqlColumn { ColumnName = "Logger", PropertyName = "Logger", DataType = SqlDbType.NVarChar }, new SqlColumn { ColumnName = "IsDeleted", PropertyName = "IsDeleted", DataType = SqlDbType.Bit }, new SqlColumn { ColumnName = "Properties", PropertyName = "Properties", DataType = SqlDbType.NVarChar } } }; columnOptions.Store.Remove(StandardColumn.TimeStamp); columnOptions.Store.Remove(StandardColumn.Id); columnOptions.Store.Remove(StandardColumn.Properties); var log = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo .MSSqlServer( connectionString: _connectionString, sinkOptions: new SinkOptions { TableName = "AutomationLogs", AutoCreateSqlTable = true }, columnOptions: columnOptions) .CreateLogger(); var parser = new MessageTemplateParser(); foreach (var serilog in request.events) { var jobId = serilog.Properties.JobId == null ? (Guid?)null : new Guid(Convert.ToString(serilog.Properties.JobId)); var automationId = serilog.Properties.AutomationId == null ? (Guid?)null : new Guid(Convert.ToString(serilog.Properties.AutomationId)); var agentId = serilog.Properties.AgentId == null ? (Guid?)null : new Guid(Convert.ToString(serilog.Properties.AgentId)); var id = Guid.NewGuid(); var timestamp = DateTimeOffset.Parse(serilog.Timestamp.ToString()).UtcDateTime; var level = (LogEventLevel)TypeDescriptor.GetConverter(typeof(LogEventLevel)).ConvertFromString(serilog.Level.ToString()); var messageTemplate = parser.Parse(serilog.MessageTemplate.ToString()); var properties = new[] { new LogEventProperty("JobId", new ScalarValue(jobId)), new LogEventProperty("AutomationId", new ScalarValue(automationId)), new LogEventProperty("AgentId", new ScalarValue(agentId)), new LogEventProperty("MachineName", new ScalarValue(serilog.Properties.MachineName.ToString())), new LogEventProperty("AgentName", new ScalarValue(serilog.Properties.AgentName.ToString())), new LogEventProperty("AutomationName", new ScalarValue(serilog.Properties.AutomationName.ToString())), new LogEventProperty("AutomationLogTimeStamp", new ScalarValue(timestamp)), new LogEventProperty("Id", new ScalarValue(id)), new LogEventProperty("CreatedOn", new ScalarValue(DateTime.UtcNow)), new LogEventProperty("Logger", new ScalarValue(logger)), new LogEventProperty("IsDeleted", new ScalarValue(false)), new LogEventProperty("Properties", new ScalarValue(serilog.Properties)), }; var logEvent = new LogEvent(timestamp, level, null, messageTemplate, properties); log.Write(logEvent); } return(Ok()); } catch (Exception ex) { ModelState.AddModelError("Logger", ex.Message); return(BadRequest(ModelState)); } }
public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter) { var level = ConvertLevel(logLevel); if (!_logger.IsEnabled(level)) { return; } var logger = _logger; string messageTemplate = null; var format = formatter ?? ((s, _) => LogFormatter.Formatter(s, null)); var structure = state as ILogValues; if (structure != null) { foreach (var property in structure.GetValues()) { if (property.Key == SerilogLoggerProvider.OriginalFormatPropertyName && property.Value is string) { messageTemplate = (string)property.Value; } else if (property.Key.StartsWith("@")) { logger = logger.ForContext(property.Key.Substring(1), property.Value, destructureObjects: true); } else { logger = logger.ForContext(property.Key, property.Value); } } var stateType = state.GetType(); var stateTypeInfo = stateType.GetTypeInfo(); // Imperfect, but at least eliminates `1 names if (messageTemplate == null && !stateTypeInfo.IsGenericType) { messageTemplate = "{" + stateType.Name + ":l}"; logger = logger.ForContext(stateType.Name, format(state, null)); } } if (messageTemplate == null && state != null) { messageTemplate = "{State:l}"; logger = logger.ForContext("State", format(state, null)); } if (string.IsNullOrEmpty(messageTemplate)) { return; } if (eventId != 0) { logger = logger.ForContext("EventId", eventId); } var parsedTemplate = _messageTemplateParser.Parse(messageTemplate); var evt = new LogEvent(DateTimeOffset.Now, level, exception, parsedTemplate, Enumerable.Empty <LogEventProperty>()); logger.Write(evt); }
public LogOutgoingMessageBehavior() { var templateParser = new MessageTemplateParser(); messageTemplate = templateParser.Parse("Sent message {OutgoingMessageType} {OutgoingMessageId}."); }
static LogEvent ReadFromJObject(int lineNumber, JObject jObject) { var timestamp = GetRequiredTimestampField(lineNumber, jObject, ClefFields.Timestamp); string messageTemplate; if (TryGetOptionalField(lineNumber, jObject, ClefFields.MessageTemplate, out var mt)) { messageTemplate = mt; } else if (TryGetOptionalField(lineNumber, jObject, ClefFields.Message, out var m)) { messageTemplate = MessageTemplateSyntax.Escape(m); } else { messageTemplate = null; } var level = LogEventLevel.Information; if (TryGetOptionalField(lineNumber, jObject, ClefFields.Level, out string l)) { level = (LogEventLevel)Enum.Parse(typeof(LogEventLevel), l); } Exception exception = null; if (TryGetOptionalField(lineNumber, jObject, ClefFields.Exception, out string ex)) { exception = TryPopulateException(ex, exception, jObject); } var parsedTemplate = messageTemplate == null ? new MessageTemplate(Enumerable.Empty <MessageTemplateToken>()) : Parser.Parse(messageTemplate); var renderings = Enumerable.Empty <Rendering>(); if (jObject.TryGetValue(ClefFields.Renderings, out JToken r)) { var renderedByIndex = r as JArray; if (renderedByIndex == null) { throw new InvalidDataException($"The `{ClefFields.Renderings}` value on line {lineNumber} is not an array as expected."); } renderings = parsedTemplate.Tokens .OfType <PropertyToken>() .Where(t => t.Format != null) .Zip(renderedByIndex, (t, rd) => new Rendering(t.PropertyName, t.Format, rd.Value <string>())) .ToArray(); } var properties = jObject .Properties() .Where(f => !ClefFields.All.Contains(f.Name)) .Select(f => { var name = ClefFields.Unescape(f.Name); var renderingsByFormat = renderings.Where(rd => rd.Name == name); return(PropertyFactory.CreateProperty(name, f.Value, renderingsByFormat)); }) .ToList(); string eventId; if (TryGetOptionalField(lineNumber, jObject, ClefFields.EventId, out eventId)) // TODO; should support numeric ids. { properties.Add(new LogEventProperty("@i", new ScalarValue(eventId))); } return(new LogEvent(timestamp, level, exception, parsedTemplate, properties)); }
public void EmptyTemplate() { _parser.Parse(""); }
public MessageTemplate Get(LogMessageTemplate template) { return(_templates.GetOrAdd(template.Format, t => TemplateParser.Parse(t))); }
public void Baseline() { var template = _parser.Parse(""); }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { var level = logLevel.ToSerilogLevel(); if (!_logger.IsEnabled(level)) { return; } var logger = _logger; string messageTemplate = null; var properties = new List <LogEventProperty>(); if (state is IEnumerable <KeyValuePair <string, object> > structure) { foreach (var property in structure) { if (string.Equals(property.Key, SerilogLoggerProvider._originalFormatPropertyName, StringComparison.OrdinalIgnoreCase) && property.Value is string value) { messageTemplate = value; } else if (property.Key.StartsWith("@", StringComparison.Ordinal)) { if (logger.BindProperty(property.Key.Substring(1), property.Value, destructureObjects: true, out var destructured)) { properties.Add(destructured); } } else { if (logger.BindProperty(property.Key, property.Value, destructureObjects: false, out var bound)) { properties.Add(bound); } } } var stateType = state.GetType(); var stateTypeInfo = stateType.GetTypeInfo(); // Imperfect, but at least eliminates `1 names if (messageTemplate == null && !stateTypeInfo.IsGenericType) { messageTemplate = "{" + stateType.Name + ":l}"; if (logger.BindProperty(stateType.Name, AsLoggableValue(state, formatter), destructureObjects: false, out var stateTypeProperty)) { properties.Add(stateTypeProperty); } } } if (messageTemplate == null) { string propertyName = null; if (state != null) { propertyName = "State"; messageTemplate = "{State:l}"; } else if (formatter != null) { propertyName = "Message"; messageTemplate = "{Message:l}"; } if (propertyName != null && logger.BindProperty(propertyName, AsLoggableValue(state, formatter), false, out var property)) { properties.Add(property); } } if (eventId.Id != 0 || eventId.Name != null) { properties.Add(CreateEventIdProperty(eventId)); } var parsedTemplate = _messageTemplateParser.Parse(messageTemplate ?? ""); var logEvent = new LogEvent(DateTimeOffset.Now, level, exception, parsedTemplate, properties); if (!(_externalScopeProvider is null)) { var stringBuilder = new StringBuilder(); _externalScopeProvider.ForEachScope( (activeScope, builder) => { if (activeScope is IReadOnlyCollection <KeyValuePair <string, object> > activeScopeDictionary) { foreach (KeyValuePair <string, object> item in activeScopeDictionary) { logEvent.AddPropertyIfAbsent(new LogEventProperty(item.Key, new ScalarValue(Convert.ToString(item.Value, CultureInfo.InvariantCulture)))); } } else { builder.Append(" => ").Append(activeScope); } }, stringBuilder); } logger.Write(logEvent); }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { var level = LevelConvert.ToSerilogLevel(logLevel); if (!_logger.IsEnabled(level)) { return; } var logger = _logger; string messageTemplate = null; var properties = new List <LogEventProperty>(); try { if (state is IEnumerable <KeyValuePair <string, object> > structure) { foreach (var property in structure) { if (property.Key == SerilogLoggerProvider.OriginalFormatPropertyName && property.Value is string value) { messageTemplate = value; } else if (property.Key.StartsWith("@")) { if (logger.BindProperty(property.Key.Substring(1), property.Value, true, out var destructured)) { properties.Add(destructured); } } else { if (logger.BindProperty(property.Key, property.Value, false, out var bound)) { properties.Add(bound); } } } var stateType = state.GetType(); var stateTypeInfo = stateType.GetTypeInfo(); // Imperfect, but at least eliminates `1 names if (messageTemplate == null && !stateTypeInfo.IsGenericType) { messageTemplate = "{" + stateType.Name + ":l}"; if (logger.BindProperty(stateType.Name, AsLoggableValue(state, formatter), false, out var stateTypeProperty)) { properties.Add(stateTypeProperty); } } } } catch (Exception e) { var ev = new LogEvent(DateTimeOffset.Now, level, e, MessageTemplateParser.Parse($"Malformed log format: {Environment.StackTrace}"), new List <LogEventProperty>()); logger.Write(ev); return; } if (messageTemplate == null) { string propertyName = null; if (state != null) { propertyName = "State"; messageTemplate = "{State:l}"; } else if (formatter != null) { propertyName = "Message"; messageTemplate = "{Message:l}"; } if (propertyName != null) { if (logger.BindProperty(propertyName, AsLoggableValue(state, formatter), false, out var property)) { properties.Add(property); } } } if (eventId.Id != 0 || eventId.Name != null) { properties.Add(CreateEventIdProperty(eventId)); } var parsedTemplate = MessageTemplateParser.Parse(messageTemplate ?? ""); var evt = new LogEvent(DateTimeOffset.Now, level, exception, parsedTemplate, properties); logger.Write(evt); }