本文整理汇总了C#中Serilog.Events.LogEvent类的典型用法代码示例。如果您正苦于以下问题:C# LogEvent类的具体用法?C# LogEvent怎么用?C# LogEvent使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
LogEvent类属于Serilog.Events命名空间,在下文中一共展示了LogEvent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Enrich
/// <summary>
/// Enrich the log event with the current ASP.NET user name, if User.Identity.IsAuthenticated is true.</summary>
/// <param name="logEvent">The log event to enrich.</param>
/// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (logEvent == null)
throw new ArgumentNullException("logEvent");
var userName = _noneUsername;
if (HttpContext.Current != null)
{
var context = new HttpContextWrapper(HttpContext.Current);
if (context.User != null)
{
if (context.User.Identity == null || context.User.Identity.IsAuthenticated == false)
{
if (_anonymousUsername != null)
userName = _anonymousUsername;
}
else
{
userName = context.User.Identity.Name;
}
}
}
if (userName == null)
return;
var userNameProperty = new LogEventProperty(UserNamePropertyName, new ScalarValue(userName));
logEvent.AddPropertyIfAbsent(userNameProperty);
}
示例2: IndexDecider_EndsUpInTheOutput
public void IndexDecider_EndsUpInTheOutput()
{
//DO NOTE that you cant send objects as scalar values through Logger.*("{Scalar}", {});
var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
const string messageTemplate = "{Song}++ @{Complex}";
var template = new MessageTemplateParser().Parse(messageTemplate);
_options.IndexDecider = (l, utcTime) => string.Format("logstash-{1}-{0:yyyy.MM.dd}", utcTime, l.Level.ToString().ToLowerInvariant());
using (var sink = new ElasticsearchSink(_options))
{
var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };
var e = new LogEvent(timestamp, LogEventLevel.Information, null, template, properties);
sink.Emit(e);
var exception = new ArgumentException("parameter");
properties = new List<LogEventProperty>
{
new LogEventProperty("Song", new ScalarValue("Old Macabre")),
new LogEventProperty("Complex", new ScalarValue(new { A = 1, B = 2}))
};
e = new LogEvent(timestamp.AddYears(-2), LogEventLevel.Fatal, exception, template, properties);
sink.Emit(e);
}
_seenHttpPosts.Should().NotBeEmpty().And.HaveCount(1);
var json = _seenHttpPosts.First();
var bulkJsonPieces = json.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
bulkJsonPieces.Should().HaveCount(4);
bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-information-2013.05.28");
bulkJsonPieces[1].Should().Contain("New Macabre");
bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-fatal-2011.05.28");
bulkJsonPieces[3].Should().Contain("Old Macabre");
//serilog by default simpy .ToString()'s unknown objects
bulkJsonPieces[3].Should().Contain("Complex\":\"{");
}
示例3: UsesCustomPropertyNames
public async Task UsesCustomPropertyNames()
{
try
{
await this.ThrowAsync();
}
catch (Exception e)
{
var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
var messageTemplate = "{Song}++";
var template = new MessageTemplateParser().Parse(messageTemplate);
using (var sink = new ElasticsearchSink(_options))
{
var properties = new List<LogEventProperty>
{
new LogEventProperty("Song", new ScalarValue("New Macabre")),
new LogEventProperty("Complex", new ScalarValue(new { A = 1, B = 2 }))
};
var logEvent = new LogEvent(timestamp, LogEventLevel.Information, e, template, properties);
//one off
sink.Emit(logEvent);
sink.Emit(logEvent);
logEvent = new LogEvent(timestamp.AddDays(2), LogEventLevel.Information, e, template, properties);
sink.Emit(logEvent);
}
var bulkJsonPieces = this.AssertSeenHttpPosts(_seenHttpPosts, 4);
bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-2013.05.28");
bulkJsonPieces[1].Should().Contain("New Macabre");
bulkJsonPieces[1].Should().NotContain("Properties\"");
bulkJsonPieces[1].Should().Contain("fields\":{");
bulkJsonPieces[1].Should().Contain("@timestamp");
bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-2013.05.30");
}
}
示例4: Emit
public void Emit(LogEvent logEvent)
{
var loggerName = "Default";
LogEventPropertyValue sourceContext;
if (logEvent.Properties.TryGetValue(Constants.SourceContextPropertyName, out sourceContext))
{
var sv = sourceContext as ScalarValue;
if (sv?.Value is string)
{
loggerName = (string) sv.Value;
}
}
var level = MapLogLevel(logEvent);
var message = logEvent.RenderMessage(_formatProvider);
var exception = logEvent.Exception;
var nlogEvent = new LogEventInfo(level, loggerName, message)
{
Exception = exception
};
foreach (var property in logEvent.Properties)
{
var sv = property.Value as ScalarValue;
var format = (sv?.Value is string) ? "l" : null;
nlogEvent.Properties[property.Key] = property.Value.ToString(format, null);
}
var logger = LogManager.GetLogger(loggerName);
logger.Log(nlogEvent);
}
示例5: Enrich
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (logEvent.Exception != null)
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("ExceptionDetail", this.DestructureException(logEvent.Exception), true));
}
}
示例6: Emit
public void Emit(LogEvent logEvent)
{
if (logEvent == null) throw new ArgumentNullException("logEvent");
var sr = new StringWriter();
_textFormatter.Format(logEvent, sr);
System.Diagnostics.Trace.Write(sr.ToString());
}
示例7: HasPropertyValue
public static void HasPropertyValue(object propertyValue, string propertyName, LogEvent logEvent)
{
HasProperty(propertyName, logEvent);
LogEventPropertyValue value = logEvent.Properties[propertyName];
Assert.That(value.LiteralValue(), Is.EqualTo(propertyValue), "The property value was not as expected");
}
示例8: Emit
public void Emit( LogEvent logEvent )
{
var stringWriter = new StringWriter();
textFormatter.Format( logEvent, stringWriter );
var message = stringWriter.ToString().Trim();
Trace.WriteLine( message );
}
示例9: Emit
/// <summary>
/// Emit the provided log event to the sink.
/// </summary>
/// <param name="logEvent">The log event to write.</param>
public void Emit(LogEvent logEvent)
{
var renderedMessage = logEvent.RenderMessage(_formatProvider);
// take logEvent and use it for the corresponding ITelemetry counterpart
if (logEvent.Exception != null)
{
var exceptionTelemetry = new ExceptionTelemetry(logEvent.Exception)
{
SeverityLevel = logEvent.Level.ToSeverityLevel(),
HandledAt = ExceptionHandledAt.UserCode,
Timestamp = logEvent.Timestamp
};
// write logEvent's .Properties to the AI one
ForwardLogEventPropertiesToTelemetryProperties(exceptionTelemetry, logEvent, renderedMessage);
_telemetryClient.TrackException(exceptionTelemetry);
}
else
{
var eventTelemetry = new EventTelemetry(logEvent.MessageTemplate.Text)
{
Timestamp = logEvent.Timestamp
};
// write logEvent's .Properties to the AI one
ForwardLogEventPropertiesToTelemetryProperties(eventTelemetry, logEvent, renderedMessage);
_telemetryClient.TrackEvent(eventTelemetry);
}
}
示例10: Emit
public void Emit(LogEvent logEvent)
{
if (logEvent == null) throw new ArgumentNullException("logEvent");
var renderSpace = new StringWriter();
_textFormatter.Format(logEvent, renderSpace);
Console.WriteLine (renderSpace.ToString ());
}
示例11: CreateLogglyEvent
private LogglyEvent CreateLogglyEvent(LogEvent logEvent)
{
var logglyEvent = new LogglyEvent();
var isHttpTransport = LogglyConfig.Instance.Transport.LogTransport == LogTransport.Https;
logglyEvent.Syslog.Level = ToSyslogLevel(logEvent);
foreach (var key in logEvent.Properties.Keys)
{
var propertyValue = logEvent.Properties[key];
var simpleValue = LogglyPropertyFormatter.Simplify(propertyValue);
logglyEvent.Data.AddIfAbsent(key, simpleValue);
}
logglyEvent.Data.AddIfAbsent("Message", logEvent.RenderMessage(_formatProvider));
if (isHttpTransport)
{
// syslog will capture these via the header
logglyEvent.Data.AddIfAbsent("Level", logEvent.Level.ToString());
}
if (logEvent.Exception != null)
{
logglyEvent.Data.AddIfAbsent("Exception", logEvent.Exception);
}
return logglyEvent;
}
示例12: Enrich
public void Enrich(LogEvent logEvent)
{
if (logEvent == null) throw new ArgumentNullException("logEvent");
if (HttpContext.Current == null)
return;
int requestId;
var requestIdItem = HttpContext.Current.Items[RequestIdItemName];
if (requestIdItem == null)
HttpContext.Current.Items[RequestIdItemName] = requestId = Interlocked.Increment(ref LastRequestId);
else
requestId = (int)requestIdItem;
string sessionId = null;
if (HttpContext.Current.Session != null)
sessionId = HttpContext.Current.Session.SessionID;
logEvent.AddPropertyIfAbsent(
LogEventProperty.For(HttpRequestPropertyName,
new
{
SessionId = sessionId,
Id = requestId,
},
destructureObjects: true));
}
示例13: Format
/// <summary>
/// Format the log event into the output.
/// </summary>
/// <param name="logEvent">The event to format.</param>
/// <param name="output">The output.</param>
public void Format(LogEvent logEvent, TextWriter output)
{
if (logEvent == null) throw new ArgumentNullException("logEvent");
if (output == null) throw new ArgumentNullException("output");
var outputProperties = OutputProperties.GetOutputProperties(logEvent);
_outputTemplate.Render(outputProperties, output, _formatProvider);
}
示例14: Enrich
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (logEvent == null) throw new ArgumentNullException("logEvent");
if (propertyFactory == null) throw new ArgumentNullException("propertyFactory");
var property = propertyFactory.CreateProperty(_name, _value, _destructureObjects);
logEvent.AddPropertyIfAbsent(property);
}
示例15: FormatContent
public static void FormatContent(LogEvent logEvent, TextWriter output)
{
if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
if (output == null) throw new ArgumentNullException(nameof(output));
output.Write("{\"Timestamp\":\"");
output.Write(logEvent.Timestamp.ToString("o"));
output.Write("\",\"Level\":\"");
output.Write(logEvent.Level);
output.Write("\",\"MessageTemplate\":");
JsonValueFormatter.WriteQuotedJsonString(logEvent.MessageTemplate.Text, output);
if (logEvent.Exception != null)
{
output.Write(",\"Exception\":");
JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
}
if (logEvent.Properties.Count != 0)
WriteProperties(logEvent.Properties, output);
var tokensWithFormat = logEvent.MessageTemplate.Tokens
.OfType<PropertyToken>()
.Where(pt => pt.Format != null);
if (tokensWithFormat.Any())
WriteRenderings(tokensWithFormat.GroupBy(pt => pt.PropertyName), logEvent.Properties, output);
output.Write('}');
}