/// <summary> /// Renders the specified environment variable and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (this.Variable != null) { builder.Append(EnvironmentHelper.GetSafeEnvironmentVariable(this.Variable)); } }
/// <summary> /// Evaluates the expression /// </summary> protected override object EvaluateNode(LogEventInfo context) { if (Inner == null) throw new InvalidOperationException("required run CreateParameters method"); return Inner.Evaluate(context); }
public static void LogEventInfoTest3() { var logEventInfo = new LogEventInfo(LogLevel.Info, "Foo", CultureInfo.InvariantCulture, "message {0}", new object[] { 1 }); Assert(logEventInfo.Context.Count == 0); logEventInfo.Context["AAA"] = "bbb"; Assert(logEventInfo.Context.Count == 1); // NLog v2 uses a wrapper here (and the property is marked as deprecated) // so make sure it is functional foreach (DictionaryEntry de in logEventInfo.Context) { Assert("AAA".Equals(de.Key)); Assert("bbb".Equals(de.Value)); } foreach (object key in logEventInfo.Context.Keys) { Assert("AAA".Equals(key)); } foreach (object value in logEventInfo.Context.Values) { Assert("bbb".Equals(value)); } }
/// <summary> /// Renders the log message including any positional parameters and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected internal override void Append(StringBuilder builder, LogEventInfo logEvent) { if (NeedPadding()) { builder.Append(ApplyPadding(logEvent.FormattedMessage)); } else { if (logEvent.Parameters == null || logEvent.Parameters.Length == 0) { builder.Append(logEvent.Message); } else { if (logEvent.FormatProvider != null) { #if NETCF builder.Append(String.Format(logEvent.FormatProvider, logEvent.Message, logEvent.Parameters)); #else builder.AppendFormat(logEvent.FormatProvider, logEvent.Message, logEvent.Parameters); #endif } else { #if NETCF builder.Append(String.Format(logEvent.Message, logEvent.Parameters)); #else builder.AppendFormat(logEvent.Message, logEvent.Parameters); #endif } }; } }
/// <summary> /// Renders the specified ASP.NET Item value and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (Variable == null) { return; } HttpContext context = HttpContext.Current; if (context == null) { return; } object value; if (EvaluateAsNestedProperties) { var path = Variable.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); value = context.Items[path[0]]; foreach (var property in path.Skip(1)) { var propertyInfo = value.GetType().GetProperty(property); value = propertyInfo.GetValue(value, null); } } else { value = context.Items[Variable]; } builder.Append(Convert.ToString(value, CultureInfo.InvariantCulture)); }
/// <summary> /// Processes the log messages. /// </summary> /// <param name="events">The events to process.</param> public void ProcessLogMessages(NLogEvents events) { var baseTimeUtc = new DateTime(events.BaseTimeUtc, DateTimeKind.Utc); var logEvents = new LogEventInfo[events.Events.Length]; // convert transport representation of log events into workable LogEventInfo[] for (int j = 0; j < events.Events.Length; ++j) { var ev = events.Events[j]; LogLevel level = LogLevel.FromOrdinal(ev.LevelOrdinal); string loggerName = events.Strings[ev.LoggerOrdinal]; var logEventInfo = new LogEventInfo(); logEventInfo.Level = level; logEventInfo.LoggerName = loggerName; logEventInfo.TimeStamp = baseTimeUtc.AddTicks(ev.TimeDelta); logEventInfo.Message = events.Strings[ev.MessageOrdinal]; logEventInfo.Properties.Add("ClientName", events.ClientName); for (int i = 0; i < events.LayoutNames.Count; ++i) { logEventInfo.Properties.Add(events.LayoutNames[i], ev.Values[i]); } logEvents[j] = logEventInfo; } this.ProcessLogMessages(logEvents); }
public void AutoFlushTargetWrapperSyncTest1() { var myTarget = new MyTarget(); var wrapper = new AutoFlushTargetWrapper { WrappedTarget = myTarget, }; myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; bool continuationHit = false; AsyncContinuation continuation = ex => { lastException = ex; continuationHit = true; }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.IsTrue(continuationHit); Assert.IsNull(lastException); Assert.AreEqual(1, myTarget.FlushCount); Assert.AreEqual(1, myTarget.WriteCount); continuationHit = false; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.IsTrue(continuationHit); Assert.IsNull(lastException); Assert.AreEqual(2, myTarget.WriteCount); Assert.AreEqual(2, myTarget.FlushCount); }
/// <summary> /// Renders the date in the long format (yyyy-MM-dd HH:mm:ss.mmm) and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected internal override void Append(StringBuilder builder, LogEventInfo logEvent) { if (NeedPadding()) { builder.Append(ApplyPadding(logEvent.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss.ffff", CultureInfo))); } else { DateTime dt = logEvent.TimeStamp; builder.Append(dt.Year); builder.Append('-'); Append2DigitsZeroPadded(builder, dt.Month); builder.Append('-'); Append2DigitsZeroPadded(builder, dt.Day); builder.Append(' '); Append2DigitsZeroPadded(builder, dt.Hour); builder.Append(':'); Append2DigitsZeroPadded(builder, dt.Minute); builder.Append(':'); Append2DigitsZeroPadded(builder, dt.Second); builder.Append('.'); Append4DigitsZeroPadded(builder, (int)(dt.Ticks % 10000000) / 1000); } }
public override string GetFormattedString(LogWriteContext context, LogEventInfo info) { StringBuilder builder = new StringBuilder(); builder.Append("Sequence: "); builder.Append(info.SequenceID); builder.Append("\r\nDate/time: "); builder.Append(info.TimeStamp.ToString(LogManager.DateTimeFormat)); builder.Append("\r\nLevel: "); builder.Append(info.Level.ToString().ToUpper()); builder.Append("\r\nThread: "); builder.Append(Environment.CurrentManagedThreadId); builder.Append("\r\nLogger: "); builder.Append(info.Logger); builder.Append("\r\n------------------------\r\n"); builder.Append(info.Message); if(info.Exception != null) { builder.Append("\r\n------------------------\r\n"); builder.Append(info.Exception); } builder.Append("\r\n------------------------\r\n"); builder.Append("Session: "); builder.Append(context.Environment.ToJson()); return builder.ToString(); }
public void TraceWrite() { _logger.Trace() .Message("This is a test fluent message.") .Property("Test", "TraceWrite") .Write(); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent message."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); } var ticks = DateTime.Now.Ticks; _logger.Trace() .Message("This is a test fluent message '{0}'.", ticks) .Property("Test", "TraceWrite") .Write(); { var rendered = string.Format("This is a test fluent message '{0}'.", ticks); var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessage("t2", rendered); } }
/// <summary> /// Writes the specified logging event to the <see cref="System.Diagnostics.Trace"/> facility. /// If the log level is greater than or equal to <see cref="LogLevel.Error"/> it uses the /// <see cref="System.Diagnostics.Trace.Fail(string)"/> method, otherwise it uses /// <see cref="System.Diagnostics.Trace.Write(string)" /> method. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { if (logEvent.Level <= LogLevel.Debug) { Trace.WriteLine(this.Layout.Render(logEvent)); } else if (logEvent.Level == LogLevel.Info) { Trace.TraceInformation(this.Layout.Render(logEvent)); } else if (logEvent.Level == LogLevel.Warn) { Trace.TraceWarning(this.Layout.Render(logEvent)); } else if (logEvent.Level == LogLevel.Error) { Trace.TraceError(this.Layout.Render(logEvent)); } else if (logEvent.Level >= LogLevel.Fatal) { Trace.Fail(this.Layout.Render(logEvent)); } else { Trace.WriteLine(this.Layout.Render(logEvent)); } }
protected override void Write(LogWriteContext context, LogEventInfo entry) { var message = Layout.GetFormattedString(context, entry); switch(entry.Level) { case LogLevel.Trace: MetroLogEventSource.Log.Trace(message); break; case LogLevel.Debug: MetroLogEventSource.Log.Debug(message); break; case LogLevel.Info: MetroLogEventSource.Log.Info(message); break; case LogLevel.Warn: MetroLogEventSource.Log.Warn(message); break; case LogLevel.Error: MetroLogEventSource.Log.Error(message); break; case LogLevel.Fatal: MetroLogEventSource.Log.Fatal(message); break; } }
/// <summary> /// Writes the specified logging event to the attached debugger. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { if (Debugger.IsLogging()) { Debugger.Log(logEvent.Level.Ordinal, logEvent.LoggerName, Layout.Render(logEvent) + "\n"); } }
/// <summary> /// Does nothing. Optionally it calculates the layout text but /// discards the results. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { if (this.FormatMessage) { this.Layout.Render(logEvent); } }
/// <summary> /// Renders the selected process information. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if(!_isInitialized) throw new InvalidOperationException("required run Initialize method"); if (propertyInfo != null) builder.Append(Convert.ToString(propertyInfo.GetValue(process, null), CultureInfo.InvariantCulture)); }
/// <summary> /// Validates that the HttpContext is available and delegates append to subclasses.<see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (HttpContextAccessor?.HttpContext == null) return; DoAppend(builder, logEvent); }
/// <summary> /// Does nothing. Optionally it calculates the layout text but /// discards the results. /// </summary> /// <param name="logEvent">The logging event.</param> protected internal override void Write(LogEventInfo logEvent) { if (_formatMessage) { CompiledLayout.GetFormattedMessage(logEvent); } }
public void CodeCompoundLayoutIsRenderedCorrectly() { var compoundLayout = new CompoundLayout { Layouts = { new SimpleLayout("Long date - ${longdate}"), new SimpleLayout("|Before| "), new JsonLayout { Attributes = { new JsonAttribute("short date", "${shortdate}"), new JsonAttribute("message", "${message}"), } }, new SimpleLayout(" |After|"), new SimpleLayout("Last - ${level}") } }; var logEventInfo = new LogEventInfo { TimeStamp = new DateTime(2010, 01, 20, 12, 34, 56), Level = LogLevel.Info, Message = "hello, world" }; const string expected = "Long date - 2010-01-20 12:34:56.0000|Before| { \"short date\": \"2010-01-20\", \"message\": \"hello, world\" } |After|Last - Info"; var actual = compoundLayout.Render(logEventInfo); Assert.Equal(expected, actual); }
/// <summary> /// Renders the specified MDC item and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { //don't use MappedDiagnosticsContext.Get to ensure we are not locking the Factory (indirect by LogManager.Configuration). var o = MappedDiagnosticsContext.GetObject(this.Item); builder.Append(o, logEvent, LoggingConfiguration); }
public void AsyncTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget); ((ISupportsInitialize)targetWrapper).Initialize(); ((ISupportsInitialize)myTarget).Initialize(); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; targetWrapper.WriteLogEvent(logEvent, continuation); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteLogEvent(logEvent, continuation); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(2, myTarget.WriteCount); }
/// <summary> /// Renders the specified environment variable and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected internal override void Append(StringBuilder builder, LogEventInfo logEvent) { if (Variable != null) { builder.Append(ApplyPadding(EnvironmentHelper.GetSafeEnvironmentVariable(Variable))); } }
/// <summary> /// Writes the specified logging event to the attached debugger. /// </summary> /// <param name="logEvent">The logging event.</param> protected internal override void Write(LogEventInfo logEvent) { if (Debugger.IsLogging()) { Debugger.Log(logEvent.Level.Ordinal, logEvent.LoggerName, CompiledLayout.GetFormattedMessage(logEvent) + "\n"); } }
/// <summary> /// Does nothing. Optionally it calculates the layout text but /// discards the results. /// </summary> /// <param name="logEvent">The logging event.</param> public override void Write(LogEventInfo logEvent) { if (_formatMessage) { CompiledLayout.GetFormattedMessage(logEvent); } }
public void FilteringTargetWrapperAsyncTest2() { var myMockCondition = new MyMockCondition(false); var myTarget = new MyAsyncTarget(); var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition); wrapper.Initialize(CommonCfg); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); Action<Exception> continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(0, myTarget.WriteCount); Assert.AreEqual(1, myMockCondition.CallCount); continuationHit.Reset(); wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(0, myTarget.WriteCount); Assert.AreEqual(2, myMockCondition.CallCount); }
public static string GetMessageInner(bool useJSON, Layout layout, LogEventInfo info) { if (!useJSON) return layout.Render(info); var logLine = new LogLine { TimeStampISO8601 = info.TimeStamp.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture), Message = info.FormattedMessage, Level = info.Level.Name, Type = "amqp", Source = new Uri(string.Format("nlog://{0}/{1}", HostName, info.LoggerName)) }; logLine.AddField("exception", info.Exception); if (info.Properties.Count > 0 && info.Properties.ContainsKey("fields")) foreach (var kv in (IEnumerable<KeyValuePair<string, object>>) info.Properties["fields"]) logLine.AddField(kv.Key, kv.Value); if (info.Properties.Count > 0 && info.Properties.ContainsKey("tags")) foreach (var tag in (IEnumerable<string>) info.Properties["tags"]) logLine.AddTag(tag); logLine.EnsureADT(); return JsonConvert.SerializeObject(logLine); }
protected override void Write(LogEventInfo logEvent) { // A log event can be either an exception OR a message. // If both were provided, then the exception takes precedence over the message. if (logEvent.Exception != null) { Metadata metaData = null; // Do we have any metadata var bugsnagInterface = logEvent.Exception as IMetadata; if (bugsnagInterface != null) { metaData = bugsnagInterface.Metadata; } AddFormattedMessageToMetadata(ref metaData, logEvent.FormattedMessage); // Notify Bugsnag of this exception. _baseClient.Value.Notify(logEvent.Exception, logEvent.Level.ToSeverity(), metaData); } else if (!string.IsNullOrWhiteSpace(logEvent.Message)) { // We don't have an exception but we do have a message! var exception = new BugsnagException(logEvent.Message); _baseClient.Value.Notify(exception, logEvent.Level.ToSeverity()); } }
protected internal override sealed Task<LogWriteOperation> WriteAsync(LogWriteContext context, LogEventInfo entry) { try { // add... List<LogEventInfo> toFlush = null; lock (_lock) { this.Buffer.Add(entry); // if... if (this.Buffer.Count >= this.Threshold) { toFlush = new List<LogEventInfo>(this.Buffer); this.Buffer = new List<LogEventInfo>(); } } // anything to flush? if (toFlush != null) return FlushAsync(context, toFlush); else return Task.FromResult(new LogWriteOperation(this, entry, true)); } catch (Exception ex) { InternalLogger.Current.Error(string.Format("Failed to write to target '{0}'.", this), ex); return Task.FromResult(new LogWriteOperation(this, entry, false)); } }
/// <summary> /// First attemps to create a RollbarClient using config read from /// appSettings. Uses properties of this class as overrides if specified. /// </summary> /// <param name="logEvent"></param> /// <returns></returns> private RollbarClient CreateClient(LogEventInfo logEvent) { var configuration = new Configuration(AccessToken); if (!string.IsNullOrEmpty(Endpoint)) configuration.Endpoint = Endpoint; if (Environment != null) configuration.Environment = Environment.Render(logEvent); if (Platform != null) configuration.Platform = Platform.Render(logEvent); if (Language != null) configuration.Language = Language.Render(logEvent); if (Framework != null) configuration.Framework = Framework.Render(logEvent); var client = new RollbarClient(configuration); client.RequestStarting += RollbarClientRequestStarting; client.RequestCompleted += RollbarClientRequestCompleted; return client; }
/// <summary> /// Renders time in the 24-h format (HH:mm:ss.mmm) and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { DateTime dt = logEvent.TimeStamp; if (this.UniversalTime) { dt = dt.ToUniversalTime(); } var culture = GetCulture(logEvent); string timeSeparator; string ticksSeparator; if (culture != null) { #if !SILVERLIGHT timeSeparator = culture.DateTimeFormat.TimeSeparator; #else timeSeparator = ":"; #endif ticksSeparator = culture.NumberFormat.NumberDecimalSeparator; } else { timeSeparator = ":"; ticksSeparator = "."; } Append2DigitsZeroPadded(builder, dt.Hour); builder.Append(timeSeparator); Append2DigitsZeroPadded(builder, dt.Minute); builder.Append(timeSeparator); Append2DigitsZeroPadded(builder, dt.Second); builder.Append(ticksSeparator); Append4DigitsZeroPadded(builder, (int)(dt.Ticks % 10000000) / 1000); }
/// <summary> /// Renders the specified ASP.NET User.Identity.AuthenticationType variable and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { HttpContext context = HttpContext.Current; if (context == null) { return; } if (context.User == null) { return; } if (context.User.Identity == null) { return; } if (!context.User.Identity.IsAuthenticated) { return; } builder.Append(context.User.Identity.AuthenticationType); }
/// <summary> /// Logs info/Error to Log file /// </summary> /// <param name="record"></param> private void log(TraceRecord record, Dictionary <string, string> requestDict) { var message = new StringBuilder(); LogEventInfo logDetailInfo = new LogEventInfo(LogLevel.FromString(record.Level.ToString()), "BilisimHRWebApiLogger", String.Empty); if (!string.IsNullOrWhiteSpace(record.Message)) { message.Append("").Append(record.Message + Environment.NewLine); } if (record.Request != null) { //GET, POST, PUT, DELETE if (record.Request.Method != null) { logDetailInfo.Properties["METHOD"] = record.Request.Method; message.Append("Method: " + record.Request.Method + Environment.NewLine); } if (record.Request.RequestUri != null) { logDetailInfo.Properties["URL"] = record.Request.RequestUri; message.Append("").Append("URL: " + record.Request.RequestUri + Environment.NewLine); } if (record.Request.Headers != null && record.Request.Headers.Contains("Authorization") && record.Request.Headers.GetValues("Authorization") != null && record.Request.Headers.GetValues("Authorization").FirstOrDefault() != null) { logDetailInfo.Properties["AUTH_TOKEN"] = record.Request.Headers.GetValues("Authorization").FirstOrDefault(); message.Append("").Append("Auth Token: " + record.Request.Headers.GetValues("Authorization").FirstOrDefault() + Environment.NewLine); } } if (!string.IsNullOrWhiteSpace(record.Category)) { message.Append("").Append(record.Category); } if (!string.IsNullOrWhiteSpace(record.Operator)) { message.Append(" ").Append(record.Operator).Append(" ").Append(record.Operation); } if (record.Exception != null && !string.IsNullOrWhiteSpace(record.Exception.GetBaseException().Message)) { var exceptionType = record.Exception.GetType(); message.Append(Environment.NewLine); if (exceptionType == typeof(WebException)) { var exception = record.Exception as WebException; if (exception != null) { message.Append("").Append("Hata Kodu: " + exception.HataKodu + Environment.NewLine); message.Append("").Append("Hata: " + exception.HataAciklama + Environment.NewLine); message.Append("").Append("Hata Detayı: " + exception.HataDetayAciklama + Environment.NewLine); message.Append("").Append("Hata Stacktrace: " + exception.StackTrace + Environment.NewLine); message.Append("").Append("HTTP Status Code: " + exception.HttpStatusCode + Environment.NewLine); } } //else if (exceptionType == typeof(ApiBusinessException)) //{ // var exception = record.Exception as ApiBusinessException; // if (exception != null) // { // message.Append("").Append("Error: " + exception.ErrorDescription + Environment.NewLine); // message.Append("").Append("Error Code: " + exception.ErrorCode + Environment.NewLine); // } //} //else if (exceptionType == typeof(ApiDataException)) //{ // var exception = record.Exception as ApiDataException; // if (exception != null) // { // message.Append("").Append("Error: " + exception.ErrorDescription + Environment.NewLine); // message.Append("").Append("Error Code: " + exception.ErrorCode + Environment.NewLine); // } //} else { message.Append("").Append("Hata: " + record.Exception.GetBaseException().Message + Environment.NewLine); message.Append("").Append("Hata Stacktrace: " + record.Exception.StackTrace + Environment.NewLine); } } logDetailInfo.Message = Convert.ToString(message) + Environment.NewLine; logDetailInfo.Properties["IP_ADDRESS"] = requestDict["IP_ADDRESS"]; logDetailInfo.Properties["CONTROLLER"] = requestDict["CONTROLLER"]; logDetailInfo.Properties["ACTION"] = requestDict["ACTION"]; logDetailInfo.Properties["USER_ID"] = requestDict["USER_ID"]; logDetailInfo.Properties["ACTION_PARAMETER"] = requestDict["ACTION_PARAMETER"]; _logger[record.Level](logDetailInfo); }
protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); }
/// <summary> /// Get the <see cref="CultureInfo"/> for rendering the messages to a <see cref="string"/>, needed for date and number formats /// </summary> /// <param name="logEvent">LogEvent with culture</param> /// <param name="layoutCulture">Culture in on Layout level</param> /// <returns></returns> /// <remarks> /// <see cref="GetFormatProvider"/> is preferred /// </remarks> protected CultureInfo GetCulture(LogEventInfo logEvent, CultureInfo layoutCulture = null) { return(logEvent.FormatProvider as CultureInfo ?? layoutCulture ?? LoggingConfiguration?.DefaultCultureInfo); }
/// <summary> /// Get the <see cref="IFormatProvider"/> for rendering the messages to a <see cref="string"/> /// </summary> /// <param name="logEvent">LogEvent with culture</param> /// <param name="layoutCulture">Culture in on Layout level</param> /// <returns></returns> protected IFormatProvider GetFormatProvider(LogEventInfo logEvent, IFormatProvider layoutCulture = null) { return(logEvent.FormatProvider ?? layoutCulture ?? LoggingConfiguration?.DefaultCultureInfo); }
/// <summary> /// Renders the value of layout renderer in the context of the specified log event into <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected abstract void Append(StringBuilder builder, LogEventInfo logEvent);
/// <summary> /// Renders the layout for the specified logging event by invoking layout renderers. /// </summary> /// <param name="logEvent">The logging event.</param> /// <returns>The rendered layout.</returns> protected override string GetFormattedMessage(LogEventInfo logEvent) { return(RenderAllocateBuilder(logEvent)); }
/// <summary> /// Renders the layout for the specified logging event by invoking layout renderers. /// </summary> /// <param name="logEvent">The logging event.</param> /// <param name="target">Initially empty <see cref="System.Text.StringBuilder"/> for the result</param> protected override void RenderFormattedMessage(LogEventInfo logEvent, System.Text.StringBuilder target) { this.Renderer.RenderAppendBuilder(logEvent, target); }
internal LogMsg Translate(LogEventInfo loggingEvent) { if (loggingEvent == null) { return(null); } //do not log our own messages. This is to prevent any sort of recursion that could happen since calling to send this will cause even more logging to happen if (loggingEvent.FormattedMessage != null && loggingEvent.FormattedMessage.IndexOf("StackifyLib:", StringComparison.OrdinalIgnoreCase) > -1) { return(null); } StackifyLib.Models.LogMsg msg = new LogMsg(); if (loggingEvent.Level != null) { msg.Level = loggingEvent.Level.Name; } if (loggingEvent.HasStackTrace && loggingEvent.UserStackFrame != null) { var frame = loggingEvent.UserStackFrame; MethodBase method = frame.GetMethod(); if (method != (MethodBase)null && method.DeclaringType != (Type)null) { if (method.DeclaringType != (Type)null) { msg.SrcMethod = method.DeclaringType.FullName + "." + method.Name; msg.SrcLine = frame.GetFileLineNumber(); } } } //if it wasn't set above for some reason we will do it this way as a fallback if (string.IsNullOrEmpty(msg.SrcMethod)) { msg.SrcMethod = loggingEvent.LoggerName; if ((logMethodNames ?? false)) { var frames = StackifyLib.Logger.GetCurrentStackTrace(loggingEvent.LoggerName, 1, true); if (frames.Any()) { var first = frames.First(); msg.SrcMethod = first.Method; msg.SrcLine = first.LineNum; } } } string formattedMessage; //Use the layout render to allow custom fields to be logged, but not if it is the default format as it logs a bunch fields we already log //really no reason to use a layout at all if (this.Layout != null && this.Layout.ToString() != "'${longdate}|${level:uppercase=true}|${logger}|${message}'") //do not use if it is the default { formattedMessage = this.Layout.Render(loggingEvent); } else { formattedMessage = loggingEvent.FormattedMessage; } msg.Msg = (formattedMessage ?? "").Trim(); object debugObject = null; if ((logAllProperties ?? true) && loggingEvent.Properties.Count > 0) { Dictionary <string, object> args = new Dictionary <string, object>(); foreach (KeyValuePair <object, object> eventProperty in loggingEvent.Properties) { string propertyKey = eventProperty.Key.ToString(); if (!string.IsNullOrEmpty(propertyKey)) { args[propertyKey] = eventProperty.Value; } } if ((logAllParams ?? false) && loggingEvent.Parameters != null && loggingEvent.Parameters.Length > 0) { debugObject = CaptureParameters(loggingEvent, msg.Msg, args); } else { debugObject = args; } } else if (loggingEvent.Parameters != null && loggingEvent.Parameters.Length > 0) { Dictionary <string, object> args = (logAllParams ?? true) ? new Dictionary <string, object>() : null; debugObject = CaptureParameters(loggingEvent, msg.Msg, args); } StackifyError error = null; if (loggingEvent.Exception != null && loggingEvent.Exception is StackifyError) { error = (StackifyError)loggingEvent.Exception; } else if (loggingEvent.Exception != null) { error = StackifyError.New((Exception)loggingEvent.Exception); } var diags = GetDiagnosticContextProperties(); if (diags != null && diags.ContainsKey("transid")) { msg.TransID = diags["transid"].ToString(); diags.Remove("transid"); } if (debugObject != null) { msg.data = StackifyLib.Utils.HelperFunctions.SerializeDebugData(debugObject, true, diags); } else { msg.data = StackifyLib.Utils.HelperFunctions.SerializeDebugData(null, false, diags); } if (msg.Msg != null && error != null) { msg.Msg += "\r\n" + error.ToString(); } else if (msg.Msg == null && error != null) { msg.Msg = error.ToString(); } if (error == null && (loggingEvent.Level == LogLevel.Error || loggingEvent.Level == LogLevel.Fatal)) { StringException stringException = new StringException(msg.Msg); stringException.TraceFrames = StackifyLib.Logger.GetCurrentStackTrace(loggingEvent.LoggerName); if (!loggingEvent.HasStackTrace || loggingEvent.UserStackFrame == null) { if (stringException.TraceFrames.Any()) { var first = stringException.TraceFrames.First(); msg.SrcMethod = first.Method; msg.SrcLine = first.LineNum; } } //Make error out of log message error = StackifyError.New(stringException); } if (error != null && !StackifyError.IgnoreError(error) && _logClient.ErrorShouldBeSent(error)) { error.SetAdditionalMessage(formattedMessage); msg.Ex = error; } else if (error != null && msg.Msg != null) { msg.Msg += " #errorgoverned"; } return(msg); }
/// <inheritdoc/> bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(); return(true); }
private string RenderSimpleLayout(string simpleLayout, string propertyName) { try { return(string.IsNullOrEmpty(simpleLayout) ? string.Empty : new SimpleLayout(simpleLayout).Render(LogEventInfo.CreateNullEvent())); } catch { return(simpleLayout); } }
public override void Write(LogEventInfo info) { target.Logger.Log(target.Logger.GetType(), ConvertLevel(info.Level), info.FormattedMessage, info.Exception); }
/// <inheritdoc/> string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) => GetStringValue(logEvent);
/// <summary> /// Evaluates the specified text by expanding all layout renderers. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <param name="logEvent">Log event to be used for evaluation.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text, LogEventInfo logEvent) { var layout = new SimpleLayout(text); return(layout.Render(logEvent)); }
protected override void Write(LogEventInfo logEvent) { }
/// <summary> /// Writes logging event to the log target. /// classes. /// </summary> /// <param name="logEvent"> /// Logging event to be written out. /// </param> protected virtual void Write(LogEventInfo logEvent) { // do nothing }
/// <summary> /// Evaluates the specified text by expanding all layout renderers /// in new <see cref="LogEventInfo" /> context. /// </summary> /// <param name="text">The text to be evaluated.</param> /// <returns>The input text with all occurrences of ${} replaced with /// values provided by the appropriate layout renderers.</returns> public static string Evaluate(string text) { return(Evaluate(text, LogEventInfo.CreateNullEvent())); }
protected override void Write(LogEventInfo logEvent) { this.WriteCount++; }
private void RunInstallCommands(InstallationContext installationContext, IEnumerable <DatabaseCommandInfo> commands) { // create log event that will be used to render all layouts LogEventInfo logEvent = installationContext.CreateLogEvent(); try { foreach (var commandInfo in commands) { string cs; if (commandInfo.ConnectionString != null) { // if there is connection string specified on the command info, use it cs = base.RenderLogEvent(commandInfo.ConnectionString, logEvent); } else if (this.InstallConnectionString != null) { // next, try InstallConnectionString cs = base.RenderLogEvent(this.InstallConnectionString, logEvent); } else { // if it's not defined, fall back to regular connection string cs = this.BuildConnectionString(logEvent); } // Set ConnectionType if it has not been initialized already if (this.ConnectionType == null) { this.SetConnectionType(); } this.EnsureConnectionOpen(cs); using (var command = this._activeConnection.CreateCommand()) { command.CommandType = commandInfo.CommandType; command.CommandText = base.RenderLogEvent(commandInfo.Text, logEvent); try { installationContext.Trace("Executing {0} '{1}'", command.CommandType, command.CommandText); command.ExecuteNonQuery(); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures) { installationContext.Warning(exception.Message); } else { installationContext.Error(exception.Message); throw; } } } } } finally { InternalLogger.Trace("DatabaseTarget: close connection after install."); this.CloseConnection(); } }
/// <summary> /// Append to target /// </summary> /// <param name="builder">The <see cref="StringBuilder" /> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(WebRootPath); }
protected override object EvaluateNode(LogEventInfo context) { this.CallCount++; return(this.result); }
/// <summary> /// Initializes the target. Can be used by inheriting classes /// to initialize logging. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); string connectionString = string.Empty; string serviceUri = string.Empty; string tenantIdentity = string.Empty; string resourceIdentity = string.Empty; Dictionary <string, string> blobMetadata = null; Dictionary <string, string> blobTags = null; var defaultLogEvent = LogEventInfo.CreateNullEvent(); try { connectionString = ConnectionString?.Render(defaultLogEvent); if (string.IsNullOrEmpty(connectionString)) { serviceUri = ServiceUri?.Render(defaultLogEvent); tenantIdentity = TenantIdentity?.Render(defaultLogEvent); resourceIdentity = ResourceIdentity?.Render(defaultLogEvent); } if (BlobMetadata?.Count > 0) { blobMetadata = new Dictionary <string, string>(); foreach (var metadata in BlobMetadata) { if (string.IsNullOrWhiteSpace(metadata.Name)) { continue; } var metadataValue = metadata.Layout?.Render(defaultLogEvent); if (string.IsNullOrEmpty(metadataValue)) { continue; } blobMetadata[metadata.Name.Trim()] = metadataValue; } } if (BlobTags?.Count > 0) { blobTags = new Dictionary <string, string>(); foreach (var tag in BlobTags) { if (string.IsNullOrWhiteSpace(tag.Name)) { continue; } var metadataValue = tag.Layout?.Render(defaultLogEvent); blobTags[tag.Name.Trim()] = metadataValue ?? string.Empty; } } _cloudBlobService.Connect(connectionString, serviceUri, tenantIdentity, resourceIdentity, blobMetadata, blobTags); InternalLogger.Trace("AzureBlobStorageTarget - Initialized"); } catch (Exception ex) { if (string.IsNullOrEmpty(connectionString) && !string.IsNullOrEmpty(serviceUri)) { InternalLogger.Error(ex, "AzureBlobStorageTarget(Name={0}): Failed to create BlobClient with ServiceUri={1}.", Name, serviceUri); } else { InternalLogger.Error(ex, "AzureBlobStorageTarget(Name={0}): Failed to create BlobClient with connectionString={1}.", Name, connectionString); } throw; } }
protected override void Write(LogEventInfo logEvent) { this.AssertExpectedUser(); this.Events.Add(logEvent); }
/// <summary> /// Returns the estimated number of characters that are needed to /// hold the rendered value for the specified logging event. /// </summary> /// <param name="logEvent">Logging event information.</param> /// <returns>The number of characters.</returns> /// <remarks> /// If the exact number is not known or /// expensive to calculate this function should return a rough estimate /// that's big enough in most cases, but not too big, in order to conserve memory. /// </remarks> protected internal override int GetEstimatedBufferSize(LogEventInfo logEvent) { return(8); }
protected override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken) { throw new NotImplementedException(); }
/// <summary> /// Outputs the rendered logging event through the <c>OutputDebugString()</c> Win32 API. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { WriteDebugString(RenderLogEvent(Layout, logEvent)); }
/// <summary> /// Renders the current log level and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected internal override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(ApplyPadding(logEvent.Level.ToString())); }
protected override void Write(LogEventInfo logEvent) { Assert.Equal(0, this.inBlockingOperation); this.WriteCount++; }
private object GetValue(LogEventInfo logEvent) { return(RenderMethod.Invoke(logEvent, LoggingConfiguration)); }
protected override void Write(LogEventInfo logEvent) { GetElasticClient().IndexDocument(GetBase_SysLogInfo(logEvent)); }
protected override void Append(System.Text.StringBuilder builder, LogEventInfo logEvent) { builder.Append("customAgnostic"); }