public static readonly string LogFilePath = "/logs/"; // /logs/ = ./logs/ /// <summary> /// Defines the log profile. /// </summary> /// <param name = "activefileLog">if set to <c>true</c> logs by file are actived.</param> /// <param name = "activeconsoleLog">if set to <c>true</c> logs on the console are actived.</param> public static void DefineLogProfile(bool activefileLog, bool activeconsoleLog) { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget { Layout = LogFormatConsole }; var fileTarget = new FileTarget { FileName = "${basedir}" + LogFilePath + "log_${date:format=dd-MM-yyyy}" + ".txt", Layout = LogFormatFile }; var fileErrorTarget = new FileTarget { FileName = "${basedir}" + LogFilePath + "error_${date:format=dd-MM-yyyy}" + ".txt", Layout = "-------------${level} at ${date:format=G}------------- ${newline} ${callsite} -> ${newline}\t${message} ${newline}-------------${level} at ${date:format=G}------------- ${newline}" }; if (activefileLog) { config.AddTarget("file", fileTarget); config.AddTarget("fileErrors", fileErrorTarget); } if (activeconsoleLog) { config.AddTarget("console", consoleTarget); } #if DEBUG var level = LogLevel.Debug; #else var level = LogLevel.Info; #endif if (activeconsoleLog) { var rule = new LoggingRule("*", level, consoleTarget); config.LoggingRules.Add(rule); } if (activefileLog) { var rule = new LoggingRule("*", level, fileTarget); rule.DisableLoggingForLevel(LogLevel.Fatal); rule.DisableLoggingForLevel(LogLevel.Error); config.LoggingRules.Add(rule); var errorRule = new LoggingRule("*", LogLevel.Warn, fileErrorTarget); config.LoggingRules.Add(errorRule); } LogManager.Configuration = config; }
/// <summary> /// Sets rule level. /// </summary> /// <param name="applicationName"> /// Name of the application. /// </param> /// <param name="ruleName"> /// Name of the rule. /// </param> /// <param name="logLevel"> /// The log level. /// </param> /// <param name="enable"> /// true to enable, false to disable. /// </param> public static void SetRuleLevel( string applicationName, string ruleName, LogLevel logLevel, bool enable) { settingsHelperLogger.Debug("Entered static method."); if (!InstanceList.ContainsKey(applicationName)) { settingsHelperLogger.Info("Configuration instance {0} does not exist.", applicationName); return; } LoggingRule loggingRule = InstanceList[applicationName].Rules[ruleName]; if (enable) { loggingRule.EnableLoggingForLevel(logLevel); } else { loggingRule.DisableLoggingForLevel(logLevel); } }
public static void DefineLogProfile(bool activefileLog, bool activeconsoleLog) { LoggingConfiguration loggingConfiguration = new LoggingConfiguration(); ColoredConsoleTarget target = new ColoredConsoleTarget { Layout = NLogHelper.LogFormatConsole }; FileTarget target2 = new FileTarget { FileName = "${basedir}" + NLogHelper.LogFilePath + "log_${date:format=dd-MM-yyyy}.txt", Layout = NLogHelper.LogFormatFile }; FileTarget target3 = new FileTarget { FileName = "${basedir}" + NLogHelper.LogFilePath + "error_${date:format=dd-MM-yyyy}.txt", Layout = "-------------${level} at ${date:format=G}------------- ${newline} ${callsite} -> ${newline}\t${message} ${newline}-------------${level} at ${date:format=G}------------- ${newline}" }; if (activefileLog) { loggingConfiguration.AddTarget("file", target2); loggingConfiguration.AddTarget("fileErrors", target3); } if (activeconsoleLog) { loggingConfiguration.AddTarget("console", target); } LogLevel debug = LogLevel.Debug; if (activeconsoleLog) { LoggingRule loggingRule = new LoggingRule("*", debug, target); loggingConfiguration.LoggingRules.Add(loggingRule); } if (activefileLog) { LoggingRule loggingRule = new LoggingRule("*", debug, target2); loggingRule.DisableLoggingForLevel(LogLevel.Fatal); loggingRule.DisableLoggingForLevel(LogLevel.Error); loggingConfiguration.LoggingRules.Add(loggingRule); LoggingRule item = new LoggingRule("*", LogLevel.Warn, target3); loggingConfiguration.LoggingRules.Add(item); } LogManager.Configuration = loggingConfiguration; }
private static void ClearLogLevels(LoggingRule loggingRule) { foreach (var logLevel in LogLevels) { if (logLevel != LogLevel.Off && loggingRule.IsLoggingEnabledForLevel(logLevel)) { loggingRule.DisableLoggingForLevel(logLevel); } } }
private static void SetLoggingLevel(LogLevel levelSet, LogLevel levelBeingSet, LoggingRule rule) { if (levelBeingSet.Ordinal >= levelSet.Ordinal) { rule.EnableLoggingForLevel(levelBeingSet); } else { rule.DisableLoggingForLevel(levelBeingSet); } }
private void SetMinimumLogLevel(LoggingRule rule, LogLevel minimumLogLevel) { foreach (var logLevel in GetLogLevels()) { if (logLevel < minimumLogLevel) { rule.DisableLoggingForLevel(logLevel); } else { rule.EnableLoggingForLevel(logLevel); } } }
private void ConfigureLogger(NLog.LogLevel nlogLogLevel) { NLogLogManager.ProviderIsAvailabileOverride = true; var config = new LoggingConfiguration(); target = new MemoryTarget(); target.Layout = "${level:uppercase=true}|${message}|${exception}"; config.AddTarget("memory", target); var loggingRule = new LoggingRule("*", LogLevel.Trace, target); loggingRule.DisableLoggingForLevel(nlogLogLevel); config.LoggingRules.Add(loggingRule); NLog.LogManager.Configuration = config; sut = new NLogLogManager().GetLogger("Test"); }
private void ConfigureLogger(NLog.LogLevel nlogLogLevel) { var config = new LoggingConfiguration(); _target = new MemoryTarget { Layout = "${level:uppercase=true}|${message}|${exception}" }; config.AddTarget("memory", _target); var loggingRule = new LoggingRule("*", NLog.LogLevel.Trace, _target); loggingRule.DisableLoggingForLevel(nlogLogLevel); config.LoggingRules.Add(loggingRule); LogManager.Configuration = config; _sut = new NLogLogProvider().GetLogger("Test"); }
public IActionResult UpdateLogLevel([FromBody] LogRulesRequest request) { Guard.NotNull(request, nameof(request)); // Checks the request is valid. if (!ModelState.IsValid) { return(ModelStateErrors.BuildErrorResponse(ModelState)); } try { foreach (LogRuleRequest logRuleRequest in request.LogRules) { LogLevel nLogLevel = logRuleRequest.LogLevel.ToNLogLevel(); LoggingRule rule = LogManager.Configuration.LoggingRules.SingleOrDefault(r => r.LoggerNamePattern == logRuleRequest.RuleName); if (rule == null) { throw new Exception($"Logger name `{logRuleRequest.RuleName}` doesn't exist."); } // Log level ordinals go from 1 to 6 (trace to fatal). // When we set a log level, we enable every log level above and disable all the ones below. foreach (LogLevel level in LogLevel.AllLoggingLevels) { if (level.Ordinal >= nLogLevel.Ordinal) { rule.EnableLoggingForLevel(level); } else { rule.DisableLoggingForLevel(level); } } } // Only update the loggers if the setting was successful. LogManager.ReconfigExistingLoggers(); return(Ok()); } catch (Exception e) { logger.LogError("Exception occurred: {0}", e.ToString()); return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString())); } }
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "ErrorEnabled": case "WarnEnabled": case "InfoEnabled": case "DebugEnabled": case "DiagEnabled": if (ErrorEnabled) { loggingRule.EnableLoggingForLevel(NLog.LogLevel.Error); loggingRule.EnableLoggingForLevel(NLog.LogLevel.Fatal); } else { loggingRule.DisableLoggingForLevel(NLog.LogLevel.Error); loggingRule.DisableLoggingForLevel(NLog.LogLevel.Fatal); } if (WarnEnabled) { loggingRule.EnableLoggingForLevel(NLog.LogLevel.Error); } else { loggingRule.DisableLoggingForLevel(NLog.LogLevel.Error); } if (InfoEnabled) { loggingRule.EnableLoggingForLevel(NLog.LogLevel.Info); } else { loggingRule.DisableLoggingForLevel(NLog.LogLevel.Info); } if (DebugEnabled) { loggingRule.EnableLoggingForLevel(NLog.LogLevel.Debug); } else { loggingRule.DisableLoggingForLevel(NLog.LogLevel.Debug); } if (DiagEnabled) { loggingRule.EnableLoggingForLevel(NLog.LogLevel.Trace); } else { loggingRule.DisableLoggingForLevel(NLog.LogLevel.Trace); } LogManager.ReconfigExistingLoggers(); break; } }
/// <summary> /// Set the level at which messages will be logged /// </summary> /// <param name="newLevel">Trace, Debug, Info, Warn, Error, Fatal, or Off</param> public static void SetLogLevel(Level newLevel) { configureLogging(); foreach (int level in Enumerable.Range(0, 6)) { if (level < (int)newLevel) { loggingRule.DisableLoggingForLevel(LogLevel.FromOrdinal(level)); } else { loggingRule.EnableLoggingForLevel(LogLevel.FromOrdinal(level)); } } LogManager.ReconfigExistingLoggers(); }
private void button1_Click(object sender, System.EventArgs e) { LoggingConfiguration config = logger1.Factory.Configuration; LoggingRule rule = config.FindRuleByName("All"); rule.DisableLoggingForLevel(LogLevel.Debug); logger1.Factory.Configuration = config; if (logger1.IsDebugEnabled) { logger1.Debug("App Log 1"); } else { logger1.Trace("App Log 1"); } }
private static void ChangeRuleMinLevel(LoggingRule rule, LogLevel minLevel) { /* * Based on how the LoggingLevel initializes its logging levels when given a minLevel, * but because LogLevel.MinLevel and LogLevel.MaxLevel are not publically accessible, * their current values are hardcoded. TODO: This is fragile! */ for (var i = LogLevel.Trace.Ordinal; i < minLevel.Ordinal; i++) { rule.DisableLoggingForLevel(LogLevel.FromOrdinal(i)); } for (var i = minLevel.Ordinal; i <= LogLevel.Fatal.Ordinal; i++) { rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i)); } LogManager.ReconfigExistingLoggers(); }
/// <summary> /// Sets rule logging level. /// </summary> /// <param name="applicationName"> /// Name of the application. /// </param> /// <param name="ruleName"> /// Name of the rule. /// </param> /// <param name="logLevel"> /// The log level. /// </param> public static void SetRuleLoggingLevel( string applicationName, string ruleName, LogLevel logLevel) { LoggingRule loggingRule = InstanceList[applicationName].Rules[ruleName]; foreach (var item in LogLevelList) { if (item >= logLevel) { loggingRule.EnableLoggingForLevel(item); } else { loggingRule.DisableLoggingForLevel(item); } } }
private void ConfigureLogger(NLog.LogLevel nlogLogLevel) { if (PerTestLogger.ShouldEnablePerTestLog()) { throw new SkipException("Unable to test NLogProvider when running in per test log mode."); } NLogLogManager.ProviderIsAvailableOverride = true; var config = new LoggingConfiguration(); target = new MemoryTarget(); target.Layout = "${level:uppercase=true}|${message}|${exception}"; config.AddTarget("memory", target); var loggingRule = new LoggingRule("*", LogLevel.Trace, target); loggingRule.DisableLoggingForLevel(nlogLogLevel); config.LoggingRules.Add(loggingRule); NLog.LogManager.Configuration = config; sut = new NLogLogManager().GetLogger("Test"); }
public static void ConfigureLog() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget(); config.AddTarget("Nutrition", fileTarget); fileTarget.FileName = @"C:\Log\HiDoctor\${shortdate}.txt"; fileTarget.Layout = "${longdate} ${message}"; fileTarget.Encoding = System.Text.Encoding.UTF8; fileTarget.ArchiveAboveSize = 10000000; fileTarget.MaxArchiveFiles = 30; fileTarget.ArchiveEvery = FileArchivePeriod.Hour; var rule = new LoggingRule("*", LogLevel.Debug, fileTarget); rule.DisableLoggingForLevel(LogLevel.Info); config.LoggingRules.Add(rule); var fileTarget2 = new FileTarget(); config.AddTarget("Nutrition", fileTarget2); fileTarget2.FileName = @"C:\Log\HiDoctor\Nutrition.txt"; fileTarget2.Layout = "${message}"; fileTarget2.Encoding = System.Text.Encoding.UTF8; fileTarget2.ArchiveAboveSize = 10000000; //fileTarget.MaxArchiveFiles = 30; fileTarget2.ArchiveEvery = FileArchivePeriod.Month; var rule2 = new LoggingRule(); rule2.EnableLoggingForLevel(LogLevel.Info); rule2.LoggerNamePattern = "*"; rule2.Targets.Add(fileTarget2); config.LoggingRules.Add(rule2); LogManager.Configuration = config; // LogManager.ThrowExceptions = true; }
public static void AddTarget(Target target, LogLevel logLevel) { if (!loggingRules.TryGetValue(logLevel, out LoggingRule lr)) { lr = new LoggingRule(); foreach (var ll in LogLevel.AllLoggingLevels) { if (ll >= logLevel) { lr.EnableLoggingForLevel(ll); } else { lr.DisableLoggingForLevel(ll); } } lr.LoggerNamePattern = "*"; LogConfiguration.LoggingRules.Add(lr); loggingRules[logLevel] = lr; } lr.Targets.Add(target); LogManager.Configuration = LogConfiguration; }
private void ConfigDatabaseTarget(LoggingConfiguration loggingConfiguration) { DatabaseTarget databaseTarget = new DatabaseTarget(); databaseTarget.DBProvider = "Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess"; databaseTarget.ConnectionString = _connectionString; databaseTarget.CommandType = System.Data.CommandType.Text; databaseTarget.CommandText = "INSERT INTO TB_SYSTEM_LOG\n" + " (MACHINE_NAME,\n" + " CALL_SITE,\n" + " USER_NAME,\n" + " LOG_DATE,\n" + " LOG_LEVEL,\n" + " LOG_MESSAGE,\n" + " LOG_EXCEPTION,\n" + " LOG_STACK_TRACE,\n" + " MONTH_NUMBER)\n" + "VALUES\n" + " (:V_MACHINE_NAME,\n" + " :V_CALL_SITE,\n" + " :V_USER_NAME,\n" + " systimestamp,\n" + " :V_LOG_LEVEL,\n" + " :V_LOG_MESSAGE,\n" + " :V_LOG_EXCEPTION,\n" + " :V_LOG_STACK_TRACE,\n" + " TO_NUMBER(TO_CHAR(SYSDATE,'MM','NLS_CALENDAR = PERSIAN')))"; //url: https://github.com/nlog/NLog/wiki/Database-target databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = ":V_MACHINE_NAME", Layout = "${machinename}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = ":V_CALL_SITE", Layout = "${callSite}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = ":V_USER_NAME", Layout = "${event-properties:item=UserName}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = ":V_LOG_LEVEL", Layout = "${level}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = ":V_LOG_MESSAGE", Layout = "${message}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = ":V_LOG_EXCEPTION", Layout = "${exception}" }); databaseTarget.Parameters.Add(new DatabaseParameterInfo { Name = ":V_LOG_STACK_TRACE", Layout = "${exception:format=Message,Type,Method,StackTrace,Data:separator=\r\n\r\n:maxInnerExceptionLevel=10:innerFormat=Message,Type,Method,StackTrace,Data:innerExceptionSeparator=\r\n\r\n}" //Layout = "${exception:format=Type,Method,StackTrace}" }); bool debugEnabled = bool.Parse(_appSettings.LoggerDebugEnabled); loggingConfiguration.AddTarget(DatabaseTargetName, databaseTarget); LoggingRule rule = new LoggingRule("*", LogLevel.Trace, databaseTarget); if (!debugEnabled) { rule.DisableLoggingForLevel(LogLevel.Debug); } loggingConfiguration.LoggingRules.Add(rule); }