private NLog.LogEventInfo ConvertToNLog(Serilog.Events.LogEvent logEvent) { var renderSpace = new StringWriter(); _textFormatter.Format(logEvent, renderSpace); var nlogEvent = new NLog.LogEventInfo { Exception = logEvent.Exception, FormatProvider = null, LoggerName = GetLoggerName(logEvent), Message = renderSpace.ToString(), Level = ConvertToNLogLevel(logEvent.Level), TimeStamp = logEvent.Timestamp.UtcDateTime, }; foreach (var property in logEvent.Properties) { var sv = property.Value as ScalarValue; var format = (sv != null && sv.Value is string) ? "l" : null; nlogEvent.Properties[property.Key] = property.Value.ToString(format, null); } return(nlogEvent); }
protected override void Append(StringBuilder builder, LogEventInfo logEvent) { var record = logEvent.Properties[NLogTraceWriter.RecordKey] as TraceRecord; if (record != null) { if (Operation) builder.Append(record.Operation); if (Status) builder.Append(record.Status.ToString()); if (StatusCode) builder.Append(Convert.ToInt32(record.Status)); if (RequestId) builder.Append(record.RequestId); if (Operator) builder.Append(record.Operator); if (Kind) builder.Append(record.Kind.ToString()); if (AcceptType) builder.Append(record.Request.Headers.Accept.ToString()); if (Host) builder.Append(record.Request.Headers.Host); } }
protected override void Write(LogEventInfo logEvent) { lock (_syncRoot) { try { if (_tableStorageManager != null) { string exceptionString = null; if (logEvent.Exception != null) exceptionString = logEvent.Exception.ToString(); LogEntry logEntry = new LogEntry(logEvent.Level.Name) { RequestIP = logEvent.Properties.ContainsKey(CustomProperties.IP_ADDRESS) ? logEvent.Properties[CustomProperties.IP_ADDRESS] as string : null, RequestUrl = logEvent.Properties.ContainsKey(CustomProperties.REQUEST_URL) ? logEvent.Properties[CustomProperties.REQUEST_URL] as string : null, ReferralUrl = logEvent.Properties.ContainsKey(CustomProperties.URL_REFERRER) ? logEvent.Properties[CustomProperties.URL_REFERRER] as string : null, Timestamp = logEvent.TimeStamp, Message = logEvent.FormattedMessage, Level = logEvent.Level.Name, Exception = exceptionString, ExceptionData = GetExceptionDataAsString(logEvent.Exception), Machine = Environment.MachineName }; _tableStorageManager.AddItemToTable(logEntry); } } catch { } } }
protected override void Append( StringBuilder builder, LogEventInfo logEvent ) { object value; if (!logEvent.Properties.TryGetValue( NLogTraceWriter.RecordKey, out value )) return; var record = value as TraceRecord; if (record == null) return; if (Operation) builder.Append( record.Operation ); if (Status) builder.Append( record.Status.ToString() ); if (StatusCode) builder.Append( Convert.ToInt32( record.Status ) ); if (RequestId) builder.Append( record.RequestId ); if (Operator) builder.Append( record.Operator ); if (Kind) builder.Append( record.Kind.ToString() ); }
protected override void Write(LogEventInfo logEvent) { if ((logEvent.Level == LogLevel.Error || logEvent.Level == LogLevel.Fatal) && logEvent.Exception != null) { SendPayload(logEvent.Level, logEvent.FormattedMessage, logEvent.Exception); } }
protected override void Write(LogEventInfo logEventInfo) { if (DocumentStore == null) DocumentStore = DependencyManager.GetInstance<IRavenDbContext>().DocumentStore; var logEvent = new LogEvent { FormattedMessage = logEventInfo.FormattedMessage, Level = logEventInfo.Level.Name, TimeStamp = logEventInfo.TimeStamp }; // Set exceptions if (logEventInfo.Exception != null) { logEvent.Exception = logEventInfo.Exception.StackTrace; if (logEventInfo.Exception.InnerException != null) { logEvent.InnerException = logEventInfo.Exception.InnerException.Message + "<br/>" + logEventInfo.Exception.InnerException.StackTrace; } } using (var session = DocumentStore.OpenSession()) { session.Store(logEvent); session.SaveChanges(); } }
public static void Log(string loggerName, LogLevel logLevel, string eventID, string message) { LogEventInfo logEvent = new LogEventInfo(logLevel, _logger.Name, message); logEvent.Properties["EventID"] = eventID; logEvent.Properties["LoggerName"] = loggerName; _logger.Log(typeof(EventLogger), logEvent); }
public static LogEventInfo Info(string loggerName, string message) { LogEventInfo evt = new LogEventInfo(LogLevel.Info, loggerName, message); evt.Properties["message"] = message; return evt; }
public MetricsCollector() { var config = ConfigurationManager.GetSection("CollectdWinConfig") as CollectdWinConfig; if (config == null) { LogEventInfo logEvent = new LogEventInfo(LogLevel.Error, Logger.Name, "Cannot get configuration section"); logEvent.Properties.Add("EventID", ErrorCodes.ERROR_CONFIGURATION_EXCEPTION); Logger.Log(logEvent); return; } _runReadThread = false; _runWriteThread = false; var registry = new PluginRegistry(); _plugins = registry.CreatePlugins(); _interval = config.GeneralSettings.Interval; if (_interval <= 10) _interval = 10; _timeout = config.GeneralSettings.Timeout; if (_timeout <= _interval) _timeout = _interval*3; bool storeRates = config.GeneralSettings.StoreRates; _aggregator = new Aggregator(_timeout, storeRates); _collectedValueQueue = new Queue<CollectableValue>(); _queueLock = new Object(); }
public void Log(LogLevel level, string message, params object[] arguments) { var info = new LogEventInfo(GetLevel(level), Key, message); info.Parameters = arguments; LogManager.GetLogger(Key).Log(info); }
/// <summary> /// 记录用户操作日志 /// </summary> /// <param name="context">日志上下文</param> public static void LogOperation(LogContext context) { try { Logger logger = NLog.LogManager.GetLogger("Operation"); if (ConfigurationManager.LoggingEnable && logger.IsInfoEnabled) { LogEventInfo log = new LogEventInfo(LogLevelConverter.Convert(context.Level), "", ""); log.Properties["type"] = context.Type; log.Properties["url"] = context.RequestUrl; log.Properties["referer"] = context.RefererUrl; log.Properties["controller"] = context.Controller; log.Properties["action"] = context.Action; log.Properties["username"] = context.Username; log.Properties["userip"] = context.UserIP; log.Properties["useragent"] = context.UserAgent; log.Message = context.Message; log.TimeStamp = context.TimeStamp; logger.Log(log); } } catch { } }
protected override void Write(LogEventInfo logEvent) { try { string message = Layout.Render(logEvent); // echo to debug Debug.WriteLine(message); ScriptObject scriptMethod = null; if (logEvent.Level == LogLevel.Info) scriptMethod = _debugInfo; else if (logEvent.Level == LogLevel.Warn) scriptMethod = _debugWarn; else if (logEvent.Level == LogLevel.Error) scriptMethod = _debugError; if (scriptMethod == null) scriptMethod = _debugLog; if (scriptMethod == null) return; // thread safe Deployment.Current.Dispatcher.BeginInvoke(() => scriptMethod.InvokeSelf(message)); } catch (Exception ex) { Debug.WriteLine("Error calling debug.log function: " + ex); } }
public static void ReportException(LogEventInfo logEvent) { try { if (RestProvider == null && EnviromentProvider.IsProduction) return; var report = new ExceptionReport(); report.LogMessage = logEvent.FormattedMessage; report.String = logEvent.Exception.ToString(); report.Logger = logEvent.LoggerName; report.Type = logEvent.Exception.GetType().Name; RestProvider.PostData(EXCEPTION_URL, report); } catch (Exception e) { if (!EnviromentProvider.IsProduction) { throw; } //this shouldn't log an exception since it will cause a recursive loop. logger.Info("Unable to report exception. " + e); } }
public ErrorFromNlog(LogEventInfo log, string applicationName = null) : base(applicationName) { if (log.Exception != null) { this.SetException(log.Exception); if (log.HasStackTrace) { this.Source = log.StackTrace.ToString(); } if (log.Properties.Count > 0) { // set context in custom data foreach (var property in log.Properties) { this.CustomData.Add(property.Key.ToString(),property.Value.ToString()); } } } else { // it's just an info this.Message = log.Message; this.Type = "NLog Message"; } this.ErrorLevel = (ErrorLevel?) log.Level.GetHashCode(); ErrorHash = GetHash(); }
private static void LogExceptionWithObjectMetadata() { var eventInfo2 = new LogEventInfo(LogLevel.Error, "MyLogName", "something broke"); eventInfo2.Exception = new Exception("This is a really bad exception"); eventInfo2.Properties.Add("CustomParameter", 987654); Log.Log(eventInfo2); }
public void ShouldHandle10NestedExceptionCorrectly() { var nestedException = new Exception("Inner Exception Detail - 10"); for (int i = 9; i > 0; i--) { var nextException = new Exception("Inner Exception Detail - " + i.ToString(), nestedException); nestedException = nextException; } var outerException = new Exception("Outer Exception Detail", nestedException); var logEvent = new LogEventInfo { Message = "Test Message", Exception = outerException }; var jsonObject = new GelfConverter().GetGelfJson(logEvent, "TestFacility"); Assert.IsNotNull(jsonObject); Assert.AreEqual("Test Message", jsonObject.Value<string>("short_message")); Assert.AreEqual("Test Message", jsonObject.Value<string>("full_message")); Assert.AreEqual(3, jsonObject.Value<int>("level")); Assert.AreEqual("TestFacility", jsonObject.Value<string>("facility")); Assert.AreEqual(null, jsonObject.Value<string>("_ExceptionSource")); const string expectedExceptionDetail = "Outer Exception Detail - Inner Exception Detail - 1 - Inner Exception Detail - 2 - Inner Exception Detail - 3 - Inner Exception Detail - 4 - Inner Exception Detail - 5 - Inner Exception Detail - 6 - Inner Exception Detail - 7 - Inner Exception Detail - 8 - Inner Exception Detail - 9 - Inner Exception Detail - 10"; Assert.AreEqual(expectedExceptionDetail, jsonObject.Value<string>("_ExceptionMessage")); Assert.AreEqual(null, jsonObject.Value<string>("_StackTrace")); Assert.AreEqual(null, jsonObject.Value<string>("_LoggerName")); }
private static Syslog.StatusCode StatusCodeFor(LogEventInfo logEventInfo) { if (logEventInfo.Level == LogLevel.Fatal || logEventInfo.Level == LogLevel.Error) return Syslog.StatusCode.Failed; return Syslog.StatusCode.OK; }
protected override void Write(LogEventInfo logEvent) { if (logEvent.Level >= LogLevel.Warn) { _logs.Add(logEvent); } }
/// <summary> /// The create log document. /// </summary> /// <param name="logEvent"> /// The log event. /// </param> /// <returns> /// The <see cref="Document"/>. /// </returns> private Document CreateLogDocument(LogEventInfo logEvent) { var log = new Document(); log["Id"] = logEvent.SequenceID; log["TimeStamp"] = logEvent.TimeStamp; log["Level"] = logEvent.Level.ToString(); log["Message"] = logEvent.Message; log["UserStackFrameNumber"] = logEvent.UserStackFrameNumber; if (logEvent.UserStackFrame != null) { log["FileName"] = logEvent.UserStackFrame.GetFileName(); log["FileLineNumber"] = logEvent.UserStackFrame.GetFileLineNumber(); log["FileColumnNumber"] = logEvent.UserStackFrame.GetFileColumnNumber(); log["MethodName"] = logEvent.UserStackFrame.GetMethod().Name; } if (logEvent.Exception != null) { log["ExceptionMessage"] = logEvent.Exception.Message; log["ExceptionHResult"] = logEvent.Exception.HResult; log["ExceptionStackTrace"] = logEvent.Exception.StackTrace; log["ExceptionSource"] = logEvent.Exception.Source; } log["UserEmail"] = logEvent.Properties["UserEmail"].ToString(); log["OrderId"] = logEvent.Properties["OrderId"].ToString(); log["PackageId"] = logEvent.Properties["PackageId"].ToString(); log["TransactionId"] = logEvent.Properties["TransactionId"].ToString(); return log; }
private Window CreateToolWindow(IDockableUserControl control) { object userControlObject = null; Window toolWindow; try { _logger.Trace("Loading \"{0}\" ClassId {1}", control.Caption, control.ClassId); toolWindow = _vbe.Windows.CreateToolWindow(_addin, _DockableWindowHost.RegisteredProgId, control.Caption, control.ClassId, ref userControlObject); } catch (COMException exception) { var logEvent = new LogEventInfo(LogLevel.Error, _logger.Name, "Error Creating Control"); logEvent.Exception = exception; logEvent.Properties.Add("EventID", 1); _logger.Error(logEvent); return null; //throw; } catch (NullReferenceException exception) { Debug.Print(exception.ToString()); return null; //throw; } var userControlHost = (_DockableWindowHost)userControlObject; toolWindow.Visible = true; //window resizing doesn't work without this EnsureMinimumWindowSize(toolWindow); toolWindow.Visible = false; //hide it again userControlHost.AddUserControl(control as UserControl); return toolWindow; }
private static void LogProgressMessage(Logger logger, LogLevel level, string message) { var logEvent = new LogEventInfo(level, logger.Name, message); logEvent.Properties.Add("Status", ""); logger.Log(logEvent); }
protected override FilterResult Check(LogEventInfo ev) { if (ev.TimeStamp.Hour >= FromHour && ev.TimeStamp.Hour <= ToHour) return Result; else return FilterResult.Neutral; }
protected override void Append(StringBuilder builder, LogEventInfo logEvent) { var jsonObject = _converter.GetGelfJson(logEvent, Facility); if (jsonObject == null) return; var jsonString = jsonObject.ToString(Formatting.None, null); builder.Append(jsonString); }
void LogEvent(LogEventInfo eventInfo) { if (eventInfo.Level == LogLevel.Fatal) { Fatals.Add(eventInfo.FormattedMessage); return; } if (eventInfo.Level == LogLevel.Error) { Errors.Add(eventInfo.FormattedMessage); return; } if (eventInfo.Level == LogLevel.Warn) { Warns.Add(eventInfo.FormattedMessage); return; } if (eventInfo.Level == LogLevel.Info) { Informations.Add(eventInfo.FormattedMessage); return; } if (eventInfo.Level == LogLevel.Debug) { Debugs.Add(eventInfo.FormattedMessage); return; } if (eventInfo.Level == LogLevel.Trace) { Traces.Add(eventInfo.FormattedMessage); // ReSharper disable RedundantJumpStatement return; // ReSharper restore RedundantJumpStatement } }
/// <summary> /// Renders the specified environmental information and appends it to the specified <see cref="T:System.Text.StringBuilder"/>. /// </summary> /// <param name="builder">The <see cref="T:System.Text.StringBuilder"/> to append the rendered data to.</param><param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { try { if (HttpContext.Current == null) return; var context = new HttpContextWrapper(HttpContext.Current); if (context.Request.RequestContext == null) return; var work = context.Request.RequestContext.GetWorkContext(); if (work == null) return; ShellSettings settings; if (!work.TryResolve(out settings)) return; builder.Append("Tenant:"); builder.AppendLine(settings.Name); } catch { } }
public void ShouldCreateGelfJsonCorrectly() { var timestamp = DateTime.Now; var logEvent = new LogEventInfo { Message = "Test Log Message", Level = LogLevel.Info, TimeStamp = timestamp, LoggerName = "GelfConverterTestLogger" }; logEvent.Properties.Add("customproperty1", "customvalue1"); logEvent.Properties.Add("customproperty2", "customvalue2"); var jsonObject = new GelfConverter().GetGelfJson(logEvent, "TestFacility"); Assert.IsNotNull(jsonObject); Assert.AreEqual("1.0", jsonObject.Value<string>("version")); Assert.AreEqual(Dns.GetHostName(), jsonObject.Value<string>("host")); Assert.AreEqual("Test Log Message", jsonObject.Value<string>("short_message")); Assert.AreEqual("Test Log Message", jsonObject.Value<string>("full_message")); Assert.AreEqual(timestamp, jsonObject.Value<DateTime>("timestamp")); Assert.AreEqual(6, jsonObject.Value<int>("level")); Assert.AreEqual("TestFacility", jsonObject.Value<string>("facility")); Assert.AreEqual("", jsonObject.Value<string>("file")); Assert.AreEqual("", jsonObject.Value<string>("line")); Assert.AreEqual("customvalue1", jsonObject.Value<string>("_customproperty1")); Assert.AreEqual("customvalue2", jsonObject.Value<string>("_customproperty2")); Assert.AreEqual("GelfConverterTestLogger", jsonObject.Value<string>("_LoggerName")); //make sure that there are no other junk in there Assert.AreEqual(12, jsonObject.Count); }
protected override void Write(LogEventInfo logEvent) { var log = new Log(); log.Time = logEvent.TimeStamp; log.Message = logEvent.FormattedMessage; log.Method = logEvent.UserStackFrame.GetMethod().Name; log.Logger = logEvent.LoggerName; if (log.Logger.StartsWith("NzbDrone.")) { log.Logger = log.Logger.Remove(0, 9); } if (logEvent.Exception != null) { if (String.IsNullOrWhiteSpace(log.Message)) { log.Message = logEvent.Exception.Message; } else { log.Message += ": " + logEvent.Exception.Message; } log.Exception = logEvent.Exception.ToString(); log.ExceptionType = logEvent.Exception.GetType().ToString(); } log.Level = logEvent.Level.Name; _database.Insert(log); }
public void Test4() { Layout l = new Layout("${rot13:${event-context:aaa}}"); LogEventInfo lei = new LogEventInfo(LogLevel.Info, "aaa", "bbb"); lei.Context["aaa"] = "HELLO"; Assert.AreEqual("URYYB", l.GetFormattedMessage(lei)); }
/// <summary> /// Add custom properties to log message. /// </summary> /// <param name="logMessage">Log message.</param> /// <param name="customProperties">Custom properties</param> private static void AddCustomProperties(NL.LogEventInfo logMessage, IEnumerable <KeyValuePair <string, object> > customProperties) { foreach (var property in customProperties) { logMessage.Properties[property.Key] = property.Value; } }
private static LogEventInfo CreateNlogEventInfo(LogEvent logEvent) { var logEventInfo = new LogEventInfo(); switch (logEvent.LogLevel) { case LogLevel.Info: logEventInfo.Level = NLog.LogLevel.Info; break; case LogLevel.Warning: logEventInfo.Level = NLog.LogLevel.Warn; break; case LogLevel.Error: logEventInfo.Level = NLog.LogLevel.Error; break; case LogLevel.Debug: logEventInfo.Level = NLog.LogLevel.Debug; break; default: throw new NotImplementedException(string.Format("Unsupported log level: {0}", logEvent.LogLevel)); } logEventInfo.Message = logEvent.Message; return logEventInfo; }
private LogEventInfo CreateLogEventInfo(NLog.LogLevel level, string message, IDictionary<string, object> dictionary, Exception exception) { LogEventInfo logEvent = new LogEventInfo(level, _logger.Name, message); foreach (var item in dictionary) { logEvent.Properties[item.Key] = item.Value; } if (exception != null) { logEvent.Properties["error-source"] = exception.Source; if (exception.TargetSite != null) { if (exception.TargetSite.DeclaringType != null) { logEvent.Properties["error-class"] = exception.TargetSite.DeclaringType.FullName; } logEvent.Properties["error-method"] = exception.TargetSite.Name; } logEvent.Properties["error-message"] = exception.Message; if (exception.InnerException != null) { logEvent.Properties["inner-error-message"] = exception.InnerException.Message; } } return logEvent; }
/// <summary> /// Format and output logvent /// </summary> /// <param name="logEvent">If caller is NLogConnector, <paramref name="logEvent"/></param>.properties will have a complete set of values of HashTag.Diagnostics.LogEvent protected override void Write(LogEventInfo logEvent) { var msg = new Dictionary<object, object>(); if (logEvent.Exception != null) { msg["exception"] = logEvent.Exception; } if (logEvent.HasStackTrace && logEvent.StackTrace != null) { msg["stackTrace"] = logEvent.StackTrace; } if (logEvent.UserStackFrame != null) { msg["userStackFrame"] = logEvent.UserStackFrame; msg["userStackFrameIndex"] = logEvent.UserStackFrameNumber; } foreach(var prop in logEvent.Properties) { msg[prop.Key] = prop.Value; } var id = msg["UUID"].ToString(); var s = JsonConvert.SerializeObject(msg,Formatting.Indented); string fileName = Path.Combine(dropFolder, id.ToString()) + ".log"; File.WriteAllText(fileName, s); }
/// <summary> /// Записать в лог /// </summary> /// <param name="logEntry">Запись</param> /// <returns>Получилось ли записать</returns> public bool Log(LogEntry logEntry) { if (_logger == null) { return(false); } var nlogEntry = new NLogInternal.LogEventInfo { LoggerName = Name }; switch (logEntry.Level) { case (ErrorLevel.None): nlogEntry.Level = NLogInternal.LogLevel.Off; break; case (ErrorLevel.Trace): nlogEntry.Level = NLogInternal.LogLevel.Trace; break; case (ErrorLevel.Debug): nlogEntry.Level = NLogInternal.LogLevel.Debug; break; case (ErrorLevel.Info): nlogEntry.Level = NLogInternal.LogLevel.Info; break; case (ErrorLevel.Warning): nlogEntry.Level = NLogInternal.LogLevel.Warn; break; case (ErrorLevel.Error): nlogEntry.Level = NLogInternal.LogLevel.Error; break; case (ErrorLevel.Fatal): nlogEntry.Level = NLogInternal.LogLevel.Fatal; break; } nlogEntry.Message = logEntry.Message; nlogEntry.TimeStamp = logEntry.TimeStamp; if (logEntry.Exception != null) { nlogEntry.Exception = logEntry.Exception; } if ((logEntry.Data != null) && (logEntry.Data.Count > 0)) { foreach (var prop in logEntry.Data) { nlogEntry.Properties.Add(prop.Key, prop.Value); } } try { if (!_logger.IsEnabled(nlogEntry.Level)) { return(false); } _logger.Log(nlogEntry); return(true); } catch (IndexOutOfRangeException) { // возникает при Level = Off return(false); } }
public static void Info(Entity.media_option_log loginfo) { NLog.LogEventInfo eventInfo = new NLog.LogEventInfo(NLog.LogLevel.Info, "", ""); foreach (var pro in typeof(Entity.media_option_log).GetProperties()) { eventInfo.Properties[pro.Name] = pro.GetValue(loginfo); } logger.Info(eventInfo); }
public static void Trace(this IAsyncInterceptor interceptor, string message, IInvocation invocation, ILogger logger) { var callerClassName = invocation.TargetType.FullName; NLog.LogEventInfo info = new NLog.LogEventInfo(NLog.LogLevel.Trace, logger.Name, message); // 呼び出し元情報を設定します。 info.SetCallerInfo(callerClassName, invocation.MethodInvocationTarget.Name, null, 0); logger.Log(typeof(TraceInterceptor), info); }
public void Log(LogEvent logEvent) { this.ExecuteWithLogCulture(() => { var messageTemplate = !string.IsNullOrEmpty(logEvent.MessageTemplate) ? logEvent.MessageTemplate : logEvent.Exception?.Message; var logMessage = new NL.LogEventInfo(LogLevels[logEvent.LogLevel], this.logger.Value.Name, null, messageTemplate, logEvent.MessageArgs, logEvent.Exception); AddCustomProperties(logMessage, logEvent.Properties.Union(this.customProperties)); this.logger.Value.Log(logMessage); }); }
/// <inheritdoc /> public void Log(Severity severity, string correlationId, string message) { var logLine = new NLog.LogEventInfo(level: Translate(severity), loggerName: null, message: message); logLine.Properties[MetaData.CorrelationId] = correlationId; _nlog.Log(logLine); if (severity == Severity.Error) { Interlocked.Increment(ref _errorCount); } }
public LogEventViewModel(NLog.LogEventInfo logEventInfo) { // TODO: Complete member initialization this.logEventInfo = logEventInfo; ToolTip = logEventInfo.FormattedMessage; Level = logEventInfo.Level.ToString(); FormattedMessage = logEventInfo.FormattedMessage; Exception = logEventInfo.Exception; LoggerName = logEventInfo.LoggerName; SetupColors(logEventInfo); }
public static void Fatal(Exception ex, string module) { lock (_sync) { var log = ServiceLocator.Current.GetInstance <ILogger>(); var e = new NLog.LogEventInfo(); e.Level = LogLevel.Fatal; e.Exception = ex; e.Properties["module"] = module; e.SetStackTrace(new StackTrace(), 1); log.Log(e); } }
public void Log(LogLevel level, string message, Exception exception, LogProperty[] properties) { var logEvent = new NLogNamespace.LogEventInfo( LogHelper.TranslateLogLevel(level), _logger.Name, null, message, null, exception) { TimeStamp = LogCastContext.PreciseNow }; if (properties != null && properties.Length > 0) { LogHelper.StoreLogProperties(logEvent, properties); } _logger.Log(logEvent); }
/// <summary> /// Writes a log entry. /// Usually it has not been used directly. /// There are lots of extension methods from "Microsoft.Extensions.Logging" nuget package. /// </summary> /// <param name="logLevel">Entry will be written on this level.</param>v /// <param name="eventId">Id of the event.</param> /// <param name="state">The entry to be written. Can be also an object.</param> /// <param name="exception">The exception related to this entry.</param> /// <param name="formatter">Function to create a <c>string</c> message of the <paramref name="state"/> and <paramref name="exception"/>.</param> public void Log <TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { var nLogLogLevel = MapMsLogLevelToNLog(logLevel); if (!IsEnabled(logLevel)) { return; } if (formatter == null) { throw new ArgumentNullException(nameof(formatter)); } var logBuilder = _logBuilder; _logBuilder = null; if (logBuilder == null) { logBuilder = new StringBuilder(); } var message = formatter(state, exception); if (_settings.IncludeScopes) { string scopeString = String.Empty; int count = GetScopeInformation(logBuilder, _scopeProvider); if (count > 0) { logBuilder.Append(message); message = logBuilder.ToString(); } } WrappedNLog.LogEventInfo logEventInfo = WrappedNLog.LogEventInfo.Create(nLogLogLevel, Logger.Name, exception, null, message); Logger.Log(logEventInfo); logBuilder.Clear(); if (logBuilder.Capacity > 1024) { logBuilder.Capacity = 1024; } _logBuilder = logBuilder; }
public override void SaveMessage(LogRecord record) { if (NLogDataProvider.Logger == null) { return; // can be null before external data providers are registered } NLog.LogLevel level = NLog.LogLevel.Off; switch (record.Level) { case Core.Log.Logging.LevelEnum.Trace: level = NLog.LogLevel.Trace; break; case Core.Log.Logging.LevelEnum.Info: level = NLog.LogLevel.Info; break; case Core.Log.Logging.LevelEnum.Warning: level = NLog.LogLevel.Warn; break; case Core.Log.Logging.LevelEnum.Error: level = NLog.LogLevel.Error; break; } if (level == NLog.LogLevel.Off) { return; } string message; if (NLogDataProvider.MessageFormat == "json") { message = Utility.JsonSerialize(record); } else { message = $"{Enc(record.Info)};{Enc(record.Category)};{Enc(record.RequestedUrl)};{record.ReferrerUrl};{record.IPAddress};{Enc(record.UserName)};{record.UserId};{record.SessionId}" + $";{record.ModuleName};{record.Class};{record.Method}" + $";{record.Namespace};{record.SiteIdentity}"; } if (NLogDataProvider.MessageEvent) { NLog.LogEventInfo ev = new NLog.LogEventInfo(level, "YetaWF", message); ev.Properties["record"] = record; NLogDataProvider.Logger.Log(ev); } else { NLogDataProvider.Logger.Log(level, message); } }
protected override void Write(NLog.LogEventInfo logEvent) { ValidateMandatoryOptions(); if (AutoCreateDatabase) { CreateDatabase(); } List <OHInfo> objectsToLog = new List <OHInfo>(); OHAuditInfo auditInfo = null; if (logEvent.Parameters != null && logEvent.Parameters.Length > 0) { for (int p = 0; p < logEvent.Parameters.Length; p++) { if (logEvent.Parameters[p] is OHAuditInfo) { auditInfo = (OHAuditInfo)logEvent.Parameters[p]; } else { OHInfo info = new OHInfo(logEvent.Parameters[p], this); if (info.IsLoggable) { objectsToLog.Add(info); } } } Data.OHDbBaseClient dbClient = OHDbFactory.GetDbClient(this); for (int i = 0; i < objectsToLog.Count; i++) { if (auditInfo != null) { objectsToLog[i].User = auditInfo.UserName; } dbClient.SaveObject(objectsToLog[i], this); } } string cs = ConnectionString; }
private void SetupColors(NLog.LogEventInfo logEventInfo) { if (logEventInfo.Level == LogLevel.Warn) { Background = Brushes.Yellow; BackgroundMouseOver = Brushes.GreenYellow; } else if (logEventInfo.Level == LogLevel.Error) { Background = Brushes.Tomato; BackgroundMouseOver = Brushes.IndianRed; } else { Background = Brushes.White; BackgroundMouseOver = Brushes.LightGray; } Foreground = Brushes.Black; ForegroundMouseOver = Brushes.Black; }
internal void Write(NLog.LogEventInfo logEvent) { string logEventLoggerFullName = logEvent.LoggerName; //filtered events, and add to events only these events coming from experiment of this logViewModel, or from TraceLab application if (logEventLoggerFullName.StartsWith("TraceLab") || logEventLoggerFullName.StartsWith(ExperimentId)) { string userFriendlySource; LogInfo info; if (logEventLoggerFullName.StartsWith("TraceLab")) { userFriendlySource = logEventLoggerFullName; info = new LogInfo { SourceName = userFriendlySource, Source = logEventLoggerFullName, Level = logEvent.Level, Message = logEvent.FormattedMessage, Exception = logEvent.Exception }; } else { string sourceAssembly, componentName; TraceLab.Core.Components.LoggerFactory.ExtractLogSourceInfo(logEventLoggerFullName, out componentName, out sourceAssembly, out userFriendlySource); info = new ComponentLogInfo { SourceName = userFriendlySource, Source = logEventLoggerFullName, Level = logEvent.Level, Message = logEvent.FormattedMessage, Exception = logEvent.Exception, ComponentName = componentName, AssemblySource = sourceAssembly }; if (logEvent.Exception != null) { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(logEvent.Exception); } } m_events.Add(info); } }
public static NLog.LogEventInfo ToNLog(this LogEventInfo logEventInfo, Exception ex) { var nlogEventInfo = new NLog.LogEventInfo { Message = logEventInfo.MessageFactory(), Level = GetNLogLevel(logEventInfo.Level), LoggerName = logEventInfo.TypeName, Exception = ex }; nlogEventInfo.Properties["Type"] = logEventInfo.TypeName; nlogEventInfo.Properties["Class"] = logEventInfo.ClassName; nlogEventInfo.Properties["Method"] = logEventInfo.MethodName; nlogEventInfo.Properties["CallContext"] = logEventInfo.CallContext; nlogEventInfo.Properties["Correlation"] = logEventInfo.Correlation; foreach (var customProperty in logEventInfo.CustomProperties) { nlogEventInfo.Properties[customProperty.Key] = customProperty.Value; } return(nlogEventInfo); }
private void LoggerContent_LinkClicked(RichTextBoxTarget sender, string linkText, NLog.LogEventInfo logEvent) { MessageBox.Show(logEvent.Exception.ToString(), "Exception details", MessageBoxButtons.OK); }
internal static void Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory) { if (targets == null) { return; } #if !NETCF bool needTrace = false; bool needTraceSources = false; int nst = targets.NeedsStackTrace; if (nst > 0) { needTrace = true; } if (nst > 1) { needTraceSources = true; } StackTrace stackTrace = null; if (needTrace && !logEvent.HasStackTrace) { int firstUserFrame = 0; stackTrace = new StackTrace(STACK_TRACE_SKIP_METHODS, needTraceSources); for (int i = 0; i < stackTrace.FrameCount; ++i) { System.Reflection.MethodBase mb = stackTrace.GetFrame(i).GetMethod(); if (mb.DeclaringType.Assembly == nlogAssembly || mb.DeclaringType == loggerType) { firstUserFrame = i + 1; } else { if (firstUserFrame != 0) { break; } } } logEvent.SetStackTrace(stackTrace, firstUserFrame); } #endif for (TargetWithFilterChain awf = targets; awf != null; awf = awf.Next) { Target app = awf.Target; FilterResult result = FilterResult.Neutral; try { FilterCollection filterChain = awf.FilterChain; for (int i = 0; i < filterChain.Count; ++i) { Filter f = filterChain[i]; result = f.Check(logEvent); if (result != FilterResult.Neutral) { break; } } if ((result == FilterResult.Ignore) || (result == FilterResult.IgnoreFinal)) { if (InternalLogger.IsDebugEnabled) { InternalLogger.Debug("{0}.{1} Rejecting message because of a filter.", logEvent.LoggerName, logEvent.Level); } if (result == FilterResult.IgnoreFinal) { return; } continue; } } catch (Exception ex) { InternalLogger.Error("FilterChain exception: {0}", ex); if (factory.ThrowExceptions) { throw; } else { continue; } } try { app.Write(logEvent); } catch (Exception ex) { InternalLogger.Error("Target exception: {0}", ex); if (factory.ThrowExceptions) { throw; } else { continue; } } if (result == FilterResult.LogFinal) { return; } } }
/// <summary> /// Writes an event message to NLog. /// </summary> /// <param name="eventSource">The event source to assocuiate with the message.</param> /// <param name="message">The message.</param> /// <param name="eventType">The event type to associate with the message.</param> /// <param name="eventId">The event id to assocuiate with the message.</param> public void WriteEvent(string eventSource, string message, EventLogEntryType eventType, int eventId) { try { if (!IsFiltered(eventId)) { NLog.LogEventInfo logEventInfo = new NLog.LogEventInfo(NLog.LogLevel.Error, _logger.Name, message); switch (eventType) { case EventLogEntryType.Error: { logEventInfo.Level = NLog.LogLevel.Error; break; } case EventLogEntryType.Warning: { logEventInfo.Level = NLog.LogLevel.Warn; break; } case EventLogEntryType.Information: { logEventInfo.Level = NLog.LogLevel.Info; break; } case EventLogEntryType.FailureAudit: { logEventInfo.Level = NLog.LogLevel.Error; break; } case EventLogEntryType.SuccessAudit: { logEventInfo.Level = NLog.LogLevel.Info; break; } default: { logEventInfo.Level = NLog.LogLevel.Error; break; } } logEventInfo.Properties.Add("EventID", eventId); logEventInfo.Properties.Add("EventSource", eventSource); _logger.Log(typeof(NlogLogger), logEventInfo); if (_forwardToEventLogger) { int maxLength = 30000; if (message.Length > maxLength) { int keepLength = maxLength - 200; // We reserve 200 bytes for the bytes removed notice. int midLength = keepLength / 2; int removed = message.Length - keepLength; message = message.Substring(0, midLength) + Environment.NewLine + "-----------------------------------------------------------" + Environment.NewLine + removed + " bytes removed due to length restrictions." + Environment.NewLine + "-----------------------------------------------------------" + Environment.NewLine + message.Substring(midLength + removed); } EventLog.WriteEntry(eventSource, message, eventType, eventId); } } } catch (Exception e) { string eventMessage = "An exception occurred while the WindowsEventLogger was trying to write an event to the Windows event log. " + Environment.NewLine + e.Message + " " + Environment.NewLine + "The original event was as follows: " + Environment.NewLine + " Event Source: " + eventSource + Environment.NewLine + " Event Type: " + eventType.ToString() + Environment.NewLine + " Event Id: " + eventId.ToString() + Environment.NewLine + " Event Message: " + message; Logger.WriteError(eventMessage, 140); throw new Exception(eventMessage, e); } }
public NLogInfo() { LogEvent = new NL.LogEventInfo(); }
internal static void Write([NotNull] Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory) { if (targets == null) { return; } StackTraceUsage stu = targets.GetStackTraceUsage(); if (stu != StackTraceUsage.None && !logEvent.HasStackTrace) { StackTrace stackTrace; #if !SILVERLIGHT stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource); #else stackTrace = new StackTrace(); #endif int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType); logEvent.SetStackTrace(stackTrace, firstUserFrame); } int originalThreadId = Thread.CurrentThread.ManagedThreadId; AsyncContinuation exceptionHandler = ex => { if (ex != null) { if (factory.ThrowExceptions && Thread.CurrentThread.ManagedThreadId == originalThreadId) { throw new NLogRuntimeException("Exception occurred in NLog", ex); } } }; for (var t = targets; t != null; t = t.NextInChain) { if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler)) { break; } } }
internal static void Write([NotNull] Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory) { if (targets == null) { return; } StackTraceUsage stu = targets.GetStackTraceUsage(); if (stu != StackTraceUsage.None && !logEvent.HasStackTrace) { StackTrace stackTrace; #if NETSTANDARD1_5 stackTrace = (StackTrace)Activator.CreateInstance(typeof(StackTrace), new object[] { stu == StackTraceUsage.WithSource }); #elif !SILVERLIGHT stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource); #else stackTrace = new StackTrace(); #endif var stackFrames = stackTrace.GetFrames(); int?firstUserFrame = FindCallingMethodOnStackTrace(stackFrames, loggerType); int?firstLegacyUserFrame = firstUserFrame.HasValue ? SkipToUserStackFrameLegacy(stackFrames, firstUserFrame.Value) : (int?)null; logEvent.GetCallSiteInformationInternal().SetStackTrace(stackTrace, firstUserFrame ?? 0, firstLegacyUserFrame); } AsyncContinuation exceptionHandler = (ex) => { }; if (factory.ThrowExceptions) { int originalThreadId = Thread.CurrentThread.ManagedThreadId; exceptionHandler = ex => { if (ex != null) { if (Thread.CurrentThread.ManagedThreadId == originalThreadId) { throw new NLogRuntimeException("Exception occurred in NLog", ex); } } }; } for (var t = targets; t != null; t = t.NextInChain) { if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler)) { break; } } }
private static bool WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException) { FilterResult result = GetFilterResult(targetListHead.FilterChain, logEvent); if ((result == FilterResult.Ignore) || (result == FilterResult.IgnoreFinal)) { if (InternalLogger.IsDebugEnabled) { InternalLogger.Debug("{0}.{1} Rejecting message because of a filter.", logEvent.LoggerName, logEvent.Level); } if (result == FilterResult.IgnoreFinal) { return(false); } return(true); } targetListHead.Target.WriteAsyncLogEvent(logEvent.WithContinuation(onException)); if (result == FilterResult.LogFinal) { return(false); } return(true); }
public static void StoreLogProperties(NLogNamespace.LogEventInfo logEvent, LogProperty[] properties) { logEvent.Properties[LogPropertiesKey] = properties; }
public void Log(N.LogEventInfo logEvent) { _logger.Log(logEvent); }
protected override void Write(NLog.LogEventInfo logEvent) { m_model.Write(logEvent); }
/// <summary> /// Process the log event /// <param name="logLevel">The log level.</param> /// <param name="loggerName">The name of the logger.</param> /// <param name="message">The log message.</param> /// <param name="arguments">The log parameters.</param> /// <param name="eventId">The event id.</param> /// <param name="eventType">The event type.</param> /// <param name="relatedActiviyId">The related activity id.</param> /// </summary> protected virtual void ProcessLogEventInfo(LogLevel logLevel, string loggerName, [Localizable(false)] string message, object[] arguments, int?eventId, TraceEventType?eventType, Guid?relatedActiviyId) { loggerName = (loggerName ?? this.Name) ?? string.Empty; StackTrace stackTrace = null; int userFrameIndex = -1; if (this.AutoLoggerName) { stackTrace = new StackTrace(); MethodBase userMethod = null; for (int i = 0; i < stackTrace.FrameCount; ++i) { var frame = stackTrace.GetFrame(i); var method = frame.GetMethod(); if (method.DeclaringType == this.GetType()) { // skip all methods of this type continue; } if (method.DeclaringType != null && method.DeclaringType.Assembly == systemAssembly) { // skip all methods from System.dll continue; } userFrameIndex = i; userMethod = method; break; } if (userFrameIndex >= 0) { if (userMethod != null && userMethod.DeclaringType != null) { loggerName = userMethod.DeclaringType.FullName; } } } ILogger logger; if (this.LogFactory != null) { logger = this.LogFactory.GetLogger(loggerName); } else { logger = LogManager.GetLogger(loggerName); } logLevel = this.forceLogLevel ?? logLevel; if (!logger.IsEnabled(logLevel)) { return; // We are done } var ev = new LogEventInfo(); ev.LoggerName = loggerName; ev.Level = logLevel; if (eventType.HasValue) { ev.Properties.Add("EventType", eventType.Value); } if (relatedActiviyId.HasValue) { ev.Properties.Add("RelatedActivityID", relatedActiviyId.Value); } ev.Message = message; ev.Parameters = arguments; ev.Level = this.forceLogLevel ?? logLevel; if (eventId.HasValue) { ev.Properties.Add("EventID", eventId.Value); } if (stackTrace != null && userFrameIndex >= 0) { ev.SetStackTrace(stackTrace, userFrameIndex); } logger.Log(ev); }
public static LogProperty[] GetLogProperties(NLogNamespace.LogEventInfo logEvent) { logEvent.Properties.TryGetValue(LogPropertiesKey, out var result); return(result as LogProperty[]); }
public void Log(Type wrapperType, N.LogEventInfo logEvent) { _logger.Log(wrapperType, logEvent); }
public virtual void ExtendLogEvent(NLog.LogEventInfo logEvent) { logEvent.Properties.Add("classname", BaseLogger.GetClassName()); }