/// <summary> /// Converts <see cref="Microsoft.Extensions.Logging.LogLevel" /> to <see cref="NLog.LogLevel" />. /// </summary> /// <param name="logLevel">Log level value to convert.</param> /// <returns>NLog value of the log level.</returns> public static LogLevel ToNLogLevel(this Microsoft.Extensions.Logging.LogLevel logLevel) { LogLevel res = LogLevel.Trace; switch (logLevel) { case Microsoft.Extensions.Logging.LogLevel.Trace: res = LogLevel.Trace; break; case Microsoft.Extensions.Logging.LogLevel.Debug: res = LogLevel.Debug; break; case Microsoft.Extensions.Logging.LogLevel.Information: res = LogLevel.Info; break; case Microsoft.Extensions.Logging.LogLevel.Warning: res = LogLevel.Warn; break; case Microsoft.Extensions.Logging.LogLevel.Error: res = LogLevel.Error; break; case Microsoft.Extensions.Logging.LogLevel.Critical: res = LogLevel.Fatal; break; } return(res); }
/// <summary> /// Logs a message. /// </summary> /// <param name="sender">The sender.</param> /// <param name="msg">The MSG.</param> /// <param name="level">The level.</param> public static void Log(string sender, string msg, NLog.LogLevel level) { if (level == NLog.LogLevel.Trace) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(DateTime.Now.ToString() + ": " + msg); Console.ResetColor(); } else if (level == NLog.LogLevel.Debug) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(DateTime.Now.ToString() + ": " + msg); Console.ResetColor(); } else if (level == NLog.LogLevel.Error) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(DateTime.Now.ToString() + ": " + msg); Console.ResetColor(); } else if (level == NLog.LogLevel.Info) { Console.WriteLine(DateTime.Now.ToString() + ": " + msg); } else if (level == NLog.LogLevel.Warn) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(DateTime.Now.ToString() + ": " + msg); Console.ResetColor(); } }
private static void CheckLogLevelMappingDictForValue(NLog.LogLevel nloglevel) { if (!_logLevelMappingDictionary.ContainsValue(nloglevel)) { throw new KeyNotFoundException(nloglevel.ToString()); } }
public static Api.LogLevel GetLogLevel(NLog.LogLevel level) { if (level.Ordinal >= NLog.LogLevel.Fatal.Ordinal) { return(Api.LogLevel.Fatal); } if (level.Ordinal >= NLog.LogLevel.Error.Ordinal) { return(Api.LogLevel.Error); } if (level.Ordinal >= NLog.LogLevel.Warn.Ordinal) { return(Api.LogLevel.Warning); } if (level.Ordinal >= NLog.LogLevel.Info.Ordinal) { return(Api.LogLevel.Info); } if (level.Ordinal >= NLog.LogLevel.Debug.Ordinal) { return(Api.LogLevel.Debug); } return(Api.LogLevel.Trace); }
private void Log( NLog.LogLevel level, Exception?exception, string?format, params object[] args) { try { var props = new AdditionalEventProperties(_accessor?.HttpContext?.User?.Identity?.Name ?? "System"); _log.WithProperty("additional", props) .Log(level, exception, format ?? string.Empty, args); } catch (ArgumentException ex) { Console.WriteLine($"Logging argument exception error: {ex.Message}"); } catch (PostgresException ex) { Console.WriteLine($"Logging database exception error: {ex.Message}"); } catch (SocketException ex) { Console.WriteLine($"Logging socket exception error: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"Logging unhandled error: {ex.Message}"); } }
public void Log(LogLevel level, string message) { NLog.LogLevel nlogLevel = NLog.LogLevel.Off; switch (level) { case LogLevel.Debug: nlogLevel = NLog.LogLevel.Debug; break; case LogLevel.Info: nlogLevel = NLog.LogLevel.Info; break; case LogLevel.Warn: nlogLevel = NLog.LogLevel.Warn; break; case LogLevel.Fatal: nlogLevel = NLog.LogLevel.Fatal; break; case LogLevel.Trace: nlogLevel = NLog.LogLevel.Trace; break; case LogLevel.Error: nlogLevel = NLog.LogLevel.Error; break; } Logger.Log(nlogLevel, message); }
private NLogger GetLogger(string loggerName, NLogLevel consoleLogLevel, NLogLevel fileLogLevel) { try { InternalLock.EnterUpgradeableReadLock(); if (ConfiguredLoggers.Any(ln => ln == loggerName)) { return(NLogManager.GetLogger(loggerName)); } try { InternalLock.EnterWriteLock(); var logger = InitializeOfflineLogger(loggerName, consoleLogLevel, fileLogLevel); ConfiguredLoggers.Add(loggerName); return(logger); } finally { if (InternalLock.IsWriteLockHeld) { InternalLock.ExitWriteLock(); } } } finally { if (InternalLock.IsUpgradeableReadLockHeld) { InternalLock.ExitUpgradeableReadLock(); } } }
public FileLog(string filename, NLog.LogLevel severity, bool utc, bool asyncLogging) { if (string.IsNullOrWhiteSpace(filename)) { throw new ArgumentException("Given filename is invalid"); } if (File.Exists(filename)) { File.Delete(filename); } // Create logging target fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read); sw = new StreamWriter(fs); if (asyncLogging) { loggingThread = new Thread(WorkerThreadMethod); messageQueue = new ConcurrentQueue <FileLogData>(); loggingThread.Start(); } // Configuration useUtcTimestamps = utc; Severity = severity; }
private static void LogEvent(NLog.LogLevel logLevel, string loggerName, string message, Exception exception, params object[] args) { NLog.LogEventInfo logEventInfo = new NLog.LogEventInfo(logLevel, loggerName, message); if (exception != null) { // Get any additional data that might have been passed into the exception.Data collection System.Text.StringBuilder sbAdditionalData = new System.Text.StringBuilder(); foreach (object key in exception.Data.Keys) { sbAdditionalData.AppendFormat("{0}: {1} ~ ", key.ToString(), exception.Data[key].ToString()); } logEventInfo.Exception = exception; logEventInfo.Properties["AdditionalData"] = sbAdditionalData.ToString(); } if (args != null) { logEventInfo.Parameters = args; } _logger.Log(logEventInfo); }
public override void LogCore(LogItem item) { NLog.LogLevel nlogLogLevel = ToNLogLevel(item.Level); //if (IsEnabled(nlogLogLevel)) //{ NLog.LogEventInfo logItem = new NLog.LogEventInfo(); logItem.Level = nlogLogLevel; logItem.TimeStamp = DateTime.UtcNow; logItem.Message = item.Message?.ToString(); logItem.Properties[CategoryContext] = item.Category; logItem.Exception = item.Exception; logItem.LoggerName = logger.Name; if (item.Properties != null) { foreach (var pair in item.Properties) { logItem.Properties.Add(pair.Key, pair.Value); } } logger.Log(logItem); if (logItem.Exception != null) { var except = logItem.Exception.ToExceptionless(); except.Submit(); } else if (item.Level == LogLevel.Error || item.Level == LogLevel.Warn || item.Level == LogLevel.Fatal || item.Level == LogLevel.Info) { ExceptionlessClient.Default.SubmitLog(item.Category, logItem.Message, ToExceptionlessLevel(item.Level)); } OutputToConsole(item); }
private Level FromNlogLevel(NLog.LogLevel nl) { if (nl.Ordinal == NLog.LogLevel.Fatal.Ordinal) { return(Level.Fatal); } else if (nl.Ordinal == NLog.LogLevel.Error.Ordinal) { return(Level.Error); } else if (nl.Ordinal == NLog.LogLevel.Debug.Ordinal) { return(Level.Debug); } else if (nl.Ordinal == NLog.LogLevel.Info.Ordinal) { return(Level.Info); } else if (nl.Ordinal == NLog.LogLevel.Warn.Ordinal) { return(Level.Warn); } else if (nl.Ordinal == NLog.LogLevel.Trace.Ordinal) { return(Level.Trace); } else if (nl.Ordinal == NLog.LogLevel.Off.Ordinal) { return(Level.Off); } else { throw new Exception("Kann den Log level nicht übersetzten!?"); } }
private void setLogLevel(NLog.LogLevel logLevel, string regex) { IList <NLog.Config.LoggingRule> rules = NLog.LogManager.Configuration.LoggingRules; //rules[0].Targets[0]. //NLog.LogManager.ReconfigExistingLoggers(); //LoggingConfiguration config = NLog.LogManager.Configuration;//new LoggingConfiguration(); //NLog.LogManager.DisableLogging(); //config.LoggingRules[0].DisableLoggingForLevel(NLog.LogLevel.Debug); //config.LoggingRules[1].DisableLoggingForLevel(NLog.LogLevel.Debug); //rules[0].EnableLoggingForLevel(NLog.LogLevel.Warn); ////rules[1].EnableLoggingForLevel(NLog.LogLevel.Warn); //NLog.LogManager.EnableLogging(); //NLog.LogManager.ReconfigExistingLoggers(); //NLog.LogManager.Configuration = config; Regex validator = new Regex(regex); foreach (var rule in rules.Where(x => validator.IsMatch(x.Targets[0].Name))) { if (!rule.IsLoggingEnabledForLevel(logLevel)) { rule.EnableLoggingForLevel(logLevel); } } }
/// <summary>记录详细日志</summary> public static void Log(NLog.LogLevel logLevel, string message, string request, string principal, string source, string content, string data) { var logger = Get <NLog.ILogger>(); var theEvent = new NLog.LogEventInfo(logLevel, logger.Name, message); if (request != null) { theEvent.Properties[nameof(PKS_Log.Request)] = request; } if (principal != null) { theEvent.Properties[nameof(PKS_Log.Principal)] = principal; } if (source != null) { theEvent.Properties[nameof(PKS_Log.ExSource)] = source; } if (content != null) { theEvent.Properties[nameof(PKS_Log.ExContent)] = content; } if (data != null) { theEvent.Properties[nameof(PKS_Log.ExData)] = data; } logger.Log(theEvent); }
public static void LogExt(this NLog.Logger logger, NLog.LogLevel level, string message, string userName, string functional) { NLog.LogEventInfo theEvent = new NLog.LogEventInfo(level, logger.Name, message); theEvent.Properties["UserName"] = userName; theEvent.Properties["Functional"] = functional; logger.Log(theEvent); }
public OperationResult(string message, NLog.LogLevel severity, NLog.Logger logger, Exception e = null) { this.Message = message; this.Severity = severity; this.Exception = e; logger.Log(severity, e, message); }
/// <summary> /// Convert NLog log level to library log level /// </summary> /// <returns>Library log level</returns> /// <param name="level">NLog log level</param> public static LogLevel ToLib(this NLog.LogLevel level) { if (level == NLog.LogLevel.Debug) { return(LogLevel.Debug); } if (level == NLog.LogLevel.Error) { return(LogLevel.Error); } if (level == NLog.LogLevel.Fatal) { return(LogLevel.Fatal); } if (level == NLog.LogLevel.Info) { return(LogLevel.Information); } if (level == NLog.LogLevel.Trace) { return(LogLevel.Trace); } if (level == NLog.LogLevel.Warn) { return(LogLevel.Warning); } return(LogLevel.Off); }
public static string ExecuteTryCatch( ConfBot config, bool answer, Func <string> action, Action <string> errorHandler) { try { return(action()); } catch (CommandException ex) { NLog.LogLevel commandErrorLevel = answer ? NLog.LogLevel.Debug : NLog.LogLevel.Warn; Log.Log(commandErrorLevel, ex, "Command Error ({0})", ex.Message); if (answer) { errorHandler(TextMod.Format(config.Commands.Color, "Error: {0}".Mod().Color(Color.Red).Bold(), ex.Message)); } } catch (Exception ex) { Log.Error(ex, "Unexpected command error: {0}", ex.UnrollException()); if (answer) { errorHandler(TextMod.Format(config.Commands.Color, "An unexpected error occured: {0}".Mod().Color(Color.Red).Bold(), ex.Message)); } } return(null); }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { NLog.LogLevel level = NLog.LogLevel.Off; switch (logLevel) { case LogLevel.Trace: level = NLog.LogLevel.Trace; break; case LogLevel.Debug: level = NLog.LogLevel.Debug; break; case LogLevel.Information: level = NLog.LogLevel.Info; break; case LogLevel.Warning: level = NLog.LogLevel.Warn; break; case LogLevel.Error: level = NLog.LogLevel.Error; break; case LogLevel.Critical: level = NLog.LogLevel.Fatal; break; case LogLevel.None: level = NLog.LogLevel.Off; break; } logger.Log(level, formatter(state, exception)); }
static Microsoft.Extensions.Logging.LogLevel ConvertToLogLevel(NLog.LogLevel logLevel) { if (logLevel == NLog.LogLevel.Trace) { return(Microsoft.Extensions.Logging.LogLevel.Trace); } else if (logLevel == NLog.LogLevel.Debug) { return(Microsoft.Extensions.Logging.LogLevel.Debug); } else if (logLevel == NLog.LogLevel.Info) { return(Microsoft.Extensions.Logging.LogLevel.Information); } else if (logLevel == NLog.LogLevel.Warn) { return(Microsoft.Extensions.Logging.LogLevel.Warning); } else if (logLevel == NLog.LogLevel.Error) { return(Microsoft.Extensions.Logging.LogLevel.Error); } else // if (logLevel == NLog.LogLevel.Fatal) { return(Microsoft.Extensions.Logging.LogLevel.Critical); } }
private void LogLazy(NLog.LogLevel level, Exception ex, string format, Func <string>[] msg) { if (_logger.IsEnabled(level)) { Log(level, ex, format, msg.Select(x => x()).ToArray()); } }
/// <inheritdoc /> public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { // First we take care about output to console. if (this.consoleLogger.IsEnabled(logLevel)) { this.consoleLogger.Log(logLevel, eventId, state, exception, (s, e) => { return(this.prefix + formatter(s, e)); }); } // The rest of the method cares about logging via NLog to files. NLog.LogLevel nLogLevel = logLevel.ToNLogLevel(); if (!this.IsEnabled(nLogLevel)) { return; } if (formatter == null) { throw new ArgumentNullException(nameof(formatter)); } string message = this.prefix + formatter(state, exception); NLog.LogEventInfo eventInfo = NLog.LogEventInfo.Create(nLogLevel, this.logger.Name, message); eventInfo.Exception = exception; this.logger.Log(this.wrapperType, eventInfo); }
public static string GetLogLevelClass(this HtmlHelper helper, NLog.LogLevel level) { if (!_logLevelToClassMap.ContainsKey(level)) { return(""); } return(_logLevelToClassMap[level]); }
public void Test_ConvertLevel_ConvertsNLogToInternalEnumeration() { NLog.LogLevel original = NLog.LogLevel.Error; LogLevel converted = LogWriter.ConvertLevel(original); Assert.AreEqual(LogLevel.Error, converted, "Didn't convert properly."); }
public void Log(LogEntry entry) { NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); NLog.LogLevel level = GetLogLevel(entry.Severity); logger.Log(level, entry.Exception, entry.Message, entry.Args); }
public GlobalLogLevelSetting GetGlobalLogLevel(NLog.LogLevel level) { GlobalLogLevelSetting val = null; LogLevel lev = level; m_globalLogLevelSettingLookup.TryGetValue(lev, out val); return(val); }
/// <summary> /// Actually sends the message to the underlying log system. /// </summary> /// <param name="logLevel">the level of this log event.</param> /// <param name="message">the message to log</param> /// <param name="exception">the exception to log (may be null)</param> protected override void WriteInternal(LogLevel logLevel, object message, Exception exception) { LogLevelNLog level = GetLevel(logLevel); NLog.LogEventInfo logEvent = new NLog.LogEventInfo(level, this.logger.Name, null, "{0}", new object[] { message }, exception); logger.Log(declaringType, logEvent); }
public static bool UnwrapToLog(this E <LocalStr> r, NLog.Logger logger, NLog.LogLevel level = null) { if (!r.Ok) { logger.Log(level ?? NLog.LogLevel.Warn, r.Error.Str); } return(r.Ok); }
public void Convert_NLogLoglevel_InLogLevel(NLog.LogLevel nlevel, WD.Logging.Abstractions.LogLevel wlevel) { // Act var result = nlevel.ToLib(); // Assert result.Should().Be(wlevel); }
internal static void LogMessage(LogEventId eventId, LogLevel level, string message, Exception exception, IDictionary <object, object> properties) { var type = typeof(T); NLog.Logger logger = NLog.LogManager.GetLogger(type.FullName); NLog.LogLevel logLevel = NLog.LogLevel.Info; // Default level to info switch (level) { case LogLevel.Warn: logLevel = NLog.LogLevel.Warn; break; case LogLevel.Info: logLevel = NLog.LogLevel.Info; break; case LogLevel.Fatal: logLevel = NLog.LogLevel.Fatal; break; case LogLevel.Error: logLevel = NLog.LogLevel.Error; break; case LogLevel.Debug: logLevel = NLog.LogLevel.Debug; break; case LogLevel.Trace: logLevel = NLog.LogLevel.Trace; break; } NLog.LogEventInfo logEvent = new NLog.LogEventInfo(logLevel, type.Name, message); logEvent.Exception = exception; CombineProperties(logEvent.Properties, properties); if (logEvent.Properties.ContainsKey(LoggingAttributes.LOG_OBJECT)) { logEvent.Properties[LoggingAttributes.LOG_OBJECT] = Newtonsoft.Json.JsonConvert.SerializeObject(logEvent.Properties[LoggingAttributes.LOG_OBJECT]); } //Add event id to the properties if (!logEvent.Properties.ContainsKey("EventId.Id")) { logEvent.Properties.Add("EventId.Id", (int)eventId); } else { logEvent.Properties["EventId.Id"] = (int)eventId; } logger.Log(type, logEvent); }
public void SendMessage(string message, NLog.LogLevel logLevel = null) { if (logLevel == null) { logLevel = NLog.LogLevel.Info; } MessageSent?.Invoke(message, logLevel); }
private void TestLogMessage(LogLevel logLevel, Exception exception, bool includeHttpContext) { var logger = includeHttpContext ? new NLogLogger(new TestApplicationSettings(), "NLogLoggerTests", GetHttpContext(false)) : new NLogLogger(new TestApplicationSettings(), "NLogLoggerTests"); var timeBeforeLog = DateTime.Now; var logMessageId = string.Empty; switch (logLevel.ToString()) { case "Debug": logMessageId = logger.Debug("This is a log message", "Some extra log details"); break; case "Info": logMessageId = logger.Info("This is a log message", "Some extra log details"); break; case "Warn": logMessageId = logger.Warn("This is a log message", "Some extra log details"); break; case "Error": logMessageId = logger.Error("This is a log message", "Some extra log details"); break; case "Fatal": logMessageId = logger.Fatal("This is a log message", exception, "Some extra log details"); break; } var timeAfterLog = DateTime.Now; var logMessage = GetLogMessageFromDatabase(logMessageId); Assert.AreEqual(Guid.Parse(logMessageId), logMessage.Id); Assert.IsTrue(logMessage.Created >= timeBeforeLog.AddMilliseconds(-timeBeforeLog.Millisecond - 1) && logMessage.Created <= timeAfterLog.AddMilliseconds(-timeAfterLog.Millisecond)); Assert.AreEqual(logLevel.ToString(), logMessage.Level); Assert.AreEqual("DEV", logMessage.Environment); Assert.AreEqual("NLogLoggerTests", logMessage.Source); Assert.AreEqual("This is a log message", logMessage.Message); Assert.AreEqual("Some extra log details", logMessage.Details); if (includeHttpContext) { Assert.AreEqual("robink", logMessage.Username); Assert.AreEqual("POST", logMessage.RequestMethod); Assert.AreEqual("http://skaele.nl", logMessage.RequestUrl); Assert.AreEqual("http://webpirates.nl", logMessage.UrlReferrer); Assert.AreEqual("Chrome", logMessage.ClientBrowser); Assert.AreEqual("127.0.0.1", logMessage.IpAddress); Assert.AreEqual("Firstname:Robin;Middlename:van der;Lastname:Knaap", logMessage.PostedFormValues); } else { Assert.AreEqual(string.Empty, logMessage.Username); Assert.AreEqual(string.Empty, logMessage.RequestMethod); Assert.AreEqual(string.Empty, logMessage.RequestUrl); Assert.AreEqual(string.Empty, logMessage.UrlReferrer); Assert.AreEqual(string.Empty, logMessage.ClientBrowser); Assert.AreEqual(string.Empty, logMessage.IpAddress); Assert.AreEqual(string.Empty, logMessage.PostedFormValues); } Assert.AreEqual("NLogLoggerTests.TestLogMessage => NLogLogger." + logLevel + " => NLogLogger.LogEvent", logMessage.StackTrace); Assert.AreEqual(exception == null ? string.Empty : "This is an exception, System.Exception, Exception, System.Exception: This is an exception, , " , logMessage.Exception); }
public void Handle(LogLevel level, string message, Exception exception) { eventMarshaller.Marshal(() => logMessageProcessor.Handle(level, message, exception)); }
internal LogLevelItem(NLog.LogLevel level, bool isEnabled, bool isLocked) { m_level = level; IsEnabled = isEnabled; IsLocked = isLocked; }
public void ReadXml(System.Xml.XmlReader reader) { m_level = NLog.LogLevel.FromString(reader.GetAttribute("Level")); IsEnabled = bool.Parse(reader.GetAttribute("IsEnabled")); reader.Read(); }
public GlobalLogLevelSetting(NLog.LogLevel level, bool isEnabled, bool isLocked) { m_level = level; IsEnabled = isEnabled; IsLocked = isLocked; }