public QueryInterceptor() { var config = new LoggingConfiguration(); var layout = "${level} ${longdate} ${logger} ${exception:format=Method} ${exception:format=Type} ${exception:format=Message} ${message} ${newline}"; var localLogLevels = new string[] { "Trace" }; var baseDirectory = @"C:\logs\query"; var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); fileTarget.FileName = $"{baseDirectory}\\{DateTime.Now.ToString("yyyy-MM-dd")}.log"; fileTarget.Layout = layout; fileTarget.KeepFileOpen = false; var filelogRule = new LoggingRule(); filelogRule.EnableLoggingForLevel(LogLevel.Trace); filelogRule.Targets.Add(fileTarget); filelogRule.LoggerNamePattern = "*"; config.LoggingRules.Add(filelogRule); LogManager.Configuration = config; _logger = LogManager.GetLogger(typeof(QueryInterceptor).ToString()); }
public void ExceptionTest() { var logioTarget = new LogIOTarget(); logioTarget.Node = "${machinename}"; logioTarget.Stream = "${logger}"; var rule = new LoggingRule("*", logioTarget); rule.EnableLoggingForLevel(LogLevel.Error); var config = new LoggingConfiguration(); config.LoggingRules.Add(rule); LogManager.Configuration = config; var logger = LogManager.GetLogger("Example"); var exception = new ArgumentException("Some random error message"); logger.Error(exception, "An exception occured"); LogManager.Flush(); }
public static void EnableWarningLogging() { if (IsWarningLoggingEnabled) { return; } LoggingConfiguration config = LogManager.Configuration; FileTarget warningTarget = new FileTarget() { Name = "fileWarnings", Layout = "${longdate} | ${level:uppercase=true} | ${logger} | ${message}", FileName = BaseLogDirectory + @"\Warning\warning.log", ArchiveFileName = BaseLogDirectory + @"\MobiBot\Warning\warning.{###}.txt", ArchiveEvery = FileArchivePeriod.Day, ArchiveNumbering = ArchiveNumberingMode.Rolling, MaxArchiveFiles = 30, NetworkWrites = true, KeepFileOpen = true }; LoggingRule warningRule = new LoggingRule("*", warningTarget); warningRule.EnableLoggingForLevel(LogLevel.Warn); config.AddTarget(warningTarget); config.LoggingRules.Add(warningRule); IsWarningLoggingEnabled = true; }
/// <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); } }
private static void SetConfiguration(string logFolder) { try { var config = new LoggingConfiguration(); var filePath = logFolder + @"\" + DateTime.Now.Day.ToString("00") + "_" + DateTime.Now.Month.ToString("00") + "_" + DateTime.Now.Year.ToString("00") + ".log"; var fileTarget = new FileTarget { Name = "ErrorLog", Layout = new SimpleLayout("${longdate} | ${level} | ${message}"), Encoding = new UTF8Encoding(), DeleteOldFileOnStartup = false, ConcurrentWrites = true, KeepFileOpen = false, CreateDirs = true, FileName = filePath, }; config.AddTarget("file", fileTarget); var rule = new LoggingRule("*", LogLevel.Debug, fileTarget); rule.EnableLoggingForLevel(LogLevel.Debug); config.LoggingRules.Add(rule); NLog.LogManager.Configuration = config; } catch { InternalLogger.LogFile = logFolder + @"internal_exceptions.log"; InternalLogger.LogWriter = new StringWriter(); InternalLogger.LogLevel = LogLevel.Fatal; } }
public void ExceptionTest() { var elasticTarget = new ElasticSearchTarget(); elasticTarget.User = "******"; elasticTarget.Password = "******"; var rule = new LoggingRule("*", elasticTarget); rule.EnableLoggingForLevel(LogLevel.Error); var config = new LoggingConfiguration(); config.LoggingRules.Add(rule); LogManager.Configuration = config; var logger = LogManager.GetLogger("Example"); var exception = new ArgumentException("Some random error message"); logger.Error(exception, "An exception occured"); LogManager.Flush(); }
private LoggerAsync() { // from Nlog documentation //step 1: config object var config = new LoggingConfiguration(); //step 2: targets var generalFileTarget = new FileTarget(); generalFileTarget.ConcurrentWrites = true; //generalFileTarget.ArchiveAboveSize = 600L * 1000L * 100L; //60 Mb generalFileTarget.ArchiveFileName = "${basedir}/archive_logs/general-{#}.log"; generalFileTarget.ArchiveEvery = FileArchivePeriod.Day; generalFileTarget.ArchiveNumbering = ArchiveNumberingMode.Date; config.AddTarget("general", generalFileTarget); var exchangeFileTarget = new FileTarget(); exchangeFileTarget.ArchiveFileName = "${basedir}/archive_logs/exchange-{#}.log"; //exchangeFileTarget.ArchiveAboveSize = 600L * 1000L * 100L; //60 Mb exchangeFileTarget.ConcurrentWrites = true; exchangeFileTarget.ArchiveEvery = FileArchivePeriod.Day; exchangeFileTarget.ArchiveNumbering = ArchiveNumberingMode.Date; config.AddTarget("exchange", exchangeFileTarget); //step 3: set target properties generalFileTarget.FileName = "${basedir}/logs/general.log"; generalFileTarget.Layout = "${longdate}|${level}|${logger}|${message}|${exception:format=ToString,StackTrace}${newline}"; exchangeFileTarget.FileName = "${basedir}/logs/exchange.log"; exchangeFileTarget.Layout = "${longdate}|${level}|${logger}|${message}|${exception:format=ToString,StackTrace}${newline}"; //step 4: set rules var generalRule = new LoggingRule("RfiCoder.*", generalFileTarget); generalRule.EnableLoggingForLevel(LogLevel.Trace); config.LoggingRules.Add(generalRule); var exchangeRule = new LoggingRule("Microsoft.Exchange.WebServices.*", NLog.LogLevel.Trace, exchangeFileTarget); config.LoggingRules.Add(exchangeRule); //step 5: activate LogManager.Configuration = config; SimpleConfigurator.ConfigureForTargetLogging(exchangeFileTarget, LogLevel.Trace); SimpleConfigurator.ConfigureForTargetLogging(generalFileTarget, LogLevel.Trace); generalLogger = NLog.LogManager.GetLogger("general"); exchangeLogger = NLog.LogManager.GetLogger("exchange"); }
public static void InitializeInternalLogging(IEnumerable <LogLevel> levels) { settingsHelperLogger.Debug("Entered static method."); if (initialized) { settingsHelperLogger.Info("Internal logging already initialized."); return; } initialized = true; SettingsHelper configuration = NewConfiguration(constAppName, constCompany); // Set up a FileTarget to log NLogConfig data under AppData\YoderZone\NLogConfig. FileTarget fileTarget = FileTargetFactory.CreateFileTarget( // Name of the target. constTarget, // The filename layout. constLogFile, // The logger's configuration instance. configuration); configuration.AddTarget(fileTarget, true); LoggingRule rule = RuleFactory.CreateRule(constLogger, fileTarget, LogLevel.Off); foreach (var logLevel in levels) { rule.EnableLoggingForLevel(logLevel); } configuration.AddRule(constRule, rule); settingsHelperLogger.Trace("Internal logging initialized."); settingsHelperLogger.Trace("Rule: {0}", constRule); settingsHelperLogger.Trace("ApplicationDataFolder = {0}", ApplicationDataFolder); settingsHelperLogger.Trace("ApplicationName = {0}", configuration.ApplicationName); settingsHelperLogger.Trace("CompanyName = {0}", configuration.CompanyName); settingsHelperLogger.Trace("fileTarget.Layout = {0}", fileTarget.Layout); settingsHelperLogger.Trace("LogFilesFolder = {0}", configuration.LogFilesFolder); settingsHelperLogger.Trace("LogFilesPath = {0}", configuration.LogFilesPath); settingsHelperLogger.Info("*** {0} ***", constAppName); settingsHelperLogger.Info("Copyright 2014 Gil Yoder"); settingsHelperLogger.Info("Licensed under Microsoft Public License (Ms-PL)"); }
public static void EnableDebugConsoleOutput() { if (IsDebugConsoleOutputEnabled) { return; } LoggingConfiguration config = LogManager.Configuration; ConsoleTarget consoleTarget = new ConsoleTarget() { Name = "consoleDebugOutput" }; LoggingRule consoleRule = new LoggingRule("*", consoleTarget); consoleRule.EnableLoggingForLevel(LogLevel.Trace); consoleRule.EnableLoggingForLevel(LogLevel.Debug); config.AddTarget(consoleTarget); config.LoggingRules.Add(consoleRule); IsDebugConsoleOutputEnabled = true; }
private static void SetLoggingLevel(LogLevel levelSet, LogLevel levelBeingSet, LoggingRule rule) { if (levelBeingSet.Ordinal >= levelSet.Ordinal) { rule.EnableLoggingForLevel(levelBeingSet); } else { rule.DisableLoggingForLevel(levelBeingSet); } }
void MvcApplication_BeginRequest(object sender, EventArgs e) { try { if (HttpContext.Current.Request.QueryString["vm"] != null && Convert.ToInt32(HttpContext.Current.Request.QueryString["vm"]) == 10) { MemoryTarget _logTarget = null; _loggerName = Guid.NewGuid().ToString().Replace("-", string.Empty); HttpContext.Current.Items.Add("LoggerName", _loggerName); _logTarget = new MemoryTarget(); _logTarget.Name = _loggerName.ToString(); LoggingRule rule = new LoggingRule(_loggerName, _logTarget); rule.EnableLoggingForLevel(LogLevel.Debug); rule.EnableLoggingForLevel(LogLevel.Trace); rule.EnableLoggingForLevel(LogLevel.Info); rule.EnableLoggingForLevel(LogLevel.Warn); rule.EnableLoggingForLevel(LogLevel.Error); rule.EnableLoggingForLevel(LogLevel.Fatal); LogManager.Configuration.LoggingRules.Add(rule); LogManager.Configuration.Reload(); } } catch (Exception ex) { LogEventInfo info = new LogEventInfo(LogLevel.Error, ECMSSettings.DEFAULT_LOGGER, ex.ToString()); ECMSLogger.Instance.Log(info); } }
private static void ConfigureLogging(bool enableVerboseLogging) { var config = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = "> ${message}"; var rule1 = new LoggingRule("*", LogLevel.Info, consoleTarget); if (enableVerboseLogging) { rule1.EnableLoggingForLevel(LogLevel.Trace); rule1.EnableLoggingForLevel(LogLevel.Debug); } config.LoggingRules.Add(rule1); LogManager.Configuration = config; }
private void SetMinimumLogLevel(LoggingRule rule, LogLevel minimumLogLevel) { foreach (var logLevel in GetLogLevels()) { if (logLevel < minimumLogLevel) { rule.DisableLoggingForLevel(logLevel); } else { rule.EnableLoggingForLevel(logLevel); } } }
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 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 static void AddRule(string name) { var configuration = LogManager.Configuration ?? new LoggingConfiguration(); var target = new FileTarget(name) { FileName = string.Format(@"${{basedir}}/{0}/{1}/log.txt", logsFolderPath, name), Layout = "Date: ${date:format=yyyy-MM-dd HH\\:mm\\:ss} | Message: ${message}" }; configuration.AddTarget(target); var rule = new LoggingRule(name, target); rule.EnableLoggingForLevel(LogLevel.Trace); configuration.LoggingRules.Add(rule); LogManager.Configuration = configuration; }
public void SimpleLogTest() { var elasticTarget = new ElasticSearchTarget(); var rule = new LoggingRule("*", elasticTarget); rule.EnableLoggingForLevel(LogLevel.Info); var config = new LoggingConfiguration(); config.LoggingRules.Add(rule); LogManager.Configuration = config; var logger = LogManager.GetLogger("Example"); logger.Info("Hello elasticsearch"); LogManager.Flush(); }
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 NLog() { NServiceBus.Logging.LogManager.Use <NLogFactory>(); var config = new LoggingConfiguration(); var infoTarget = new ColoredConsoleTarget { Layout = "${message}${newline}" }; infoTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule() { Regex = @"^Order\s+[a-fA-F0-9]+-[a-fA-F0-9]+-[a-fA-F0-9]+-[a-fA-F0-9]+-[a-fA-F0-9]+\s*:", ForegroundColor = ConsoleOutputColor.Yellow }); infoTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule() { Regex = @"^Order\s+[a-fA-F0-9]+-[a-fA-F0-9]+-[a-fA-F0-9]+-[a-fA-F0-9]+-[a-fA-F0-9]+\s*:(.*)", ForegroundColor = ConsoleOutputColor.Cyan }); var errorTarget = new ColoredConsoleTarget { Layout = "${level}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}" }; config.AddTarget("console", infoTarget); var infoRule = new LoggingRule("*", infoTarget); infoRule.EnableLoggingForLevel(LogLevel.Info); config.LoggingRules.Add(infoRule); config.AddTarget("errors", errorTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Warn, errorTarget)); LogManager.Configuration = config; }
private static Logger ConfigureLogger(LogLevel level) { var config = new LoggingConfiguration(); var elasticTarget = new DataDogTarget { // IMPORTANT! replace "YOUR API KEY" with your DataDog API key ApiKey = "YOUR API KEY", Service = Assembly.GetExecutingAssembly()?.GetName().Name, Source = Environment.MachineName }; var rule = new LoggingRule("*", elasticTarget); rule.EnableLoggingForLevel(level); config.AddTarget(elasticTarget); config.LoggingRules.Add(rule); var consoleTarget = new ConsoleTarget("console"); var consoleRule = new LoggingRule("*", consoleTarget); consoleRule.EnableLoggingForLevel(level); config.AddTarget(consoleTarget); config.LoggingRules.Add(consoleRule); var debugTarget = new DebugTarget("debug"); var debugRule = new LoggingRule("*", debugTarget); debugRule.EnableLoggingForLevel(level); config.AddTarget(debugTarget); config.LoggingRules.Add(debugRule); LogManager.Configuration = config; var logger = LogManager.GetLogger("Example"); return(logger); }
public void SimpleJsonLayoutTest() { var elasticTarget = new ElasticSearchTarget(); elasticTarget.EnableJsonLayout = true; elasticTarget.Layout = new JsonLayout() { MaxRecursionLimit = 10, IncludeAllProperties = true, Attributes = { new JsonAttribute("timestamp", "${date:universaltime=true:format=o}"), new JsonAttribute("lvl", "${level}"), new JsonAttribute("msg", "${message}"), new JsonAttribute("logger", "${logger}"), new JsonAttribute("threadid", "${threadid}", false), // Skip quotes for integer-value } }; var rule = new LoggingRule("*", elasticTarget); rule.EnableLoggingForLevel(LogLevel.Info); var config = new LoggingConfiguration(); config.LoggingRules.Add(rule); LogManager.ThrowExceptions = true; LogManager.Configuration = config; var logger = LogManager.GetLogger("Example"); logger.Info("Hello elasticsearch"); LogManager.Flush(); }
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; }
//class TestLogManager //{ // // A Logger dispenser for the current configuration (Remember to call Flush on application exit) // public static LogFactory Instance { get { return instance.Value; } } // private static Lazy<LogFactory> instance = new Lazy<LogFactory>(BuildLogFactory); // private static LogFactory BuildLogFactory() // { // // Initialize LogFactory object // LogFactory logFactory = new LogFactory(); // // Initialize LogFactory Configuration // LoggingConfiguration config = new LoggingConfiguration(); // // Register the custom layout to show stack trace in logs // LayoutRenderer.Register("IndentationLayout", typeof(IndentationLayoutRenderer)); //no space // // Initialize File Target // var fileTarget = new FileTarget("File Target") // { // FileName = "${basedir}/logs/logTest.xml", // DeleteOldFileOnStartup = true, // Deletes old log file every time log is called. Set to true simply for testing purposes // KeepFileOpen = true, // Keeps file open regardless of logger status. (Increases performance) // OpenFileCacheTimeout = 30, // Max number of seconds file is kept open. (Increases performance, but the value will scale with the scope of logger implementation) // Layout = "${IndentationLayout} ${longdate} | ${level:uppercase=true} | ${logger} | ${message} | ${callsite:className=true:fileName=false:includeSourcePath=false:methodName=true}" //use IndentationLayout // }; // // Initialize the AsyncWrapper for the fileTarget // AsyncTargetWrapper fileWrapper = new AsyncTargetWrapper(); // fileWrapper.WrappedTarget = fileTarget; // fileWrapper.QueueLimit = 5000; // Limits number of requests in the request queue (Improves performance) // fileWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block; // Blocks incoming requests until request queue if has space // // Initialize the AsyncFlushTargetWrapper for the FileWrapper // AutoFlushTargetWrapper fileFlushWrapper = new AutoFlushTargetWrapper(); // fileFlushWrapper.WrappedTarget = fileWrapper; // // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule // fileFlushWrapper.Condition = "level >= LogLevel.Info"; // // Adding the target to the config // config.AddTarget("file", fileFlushWrapper); // // Creating the Log Level rules for each target and adding them to the config // var fileRule = new LoggingRule("*", fileTarget); // fileRule.EnableLoggingForLevel(exceptionLevel); // fileRule.EnableLoggingForLevels(minLevel, maxLevel); // config.LoggingRules.Add(fileRule); // // Assigning the configuration to the logger // logFactory.Configuration = config; // return logFactory; // } //} private void SetupLoggingConfiguration() { // Intialize Config Object LoggingConfiguration config = new LoggingConfiguration(); LayoutRenderer.Register("IndentationLayout", typeof(IndentationLayoutRenderer)); //no space /* * // Initialize Console Target * var consoleTarget = new ColoredConsoleTarget("Console Target") * { * Layout = @"${time} ${longdate} ${uppercase: ${level}} ${logger} ${message} ${exception: format=ToString}" * }; * * // Initialize the AsyncWrapper for the ConsoleTarget * AsyncTargetWrapper consoleWrapper = new AsyncTargetWrapper(); * consoleWrapper.WrappedTarget = consoleTarget; * consoleWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block; * consoleWrapper.QueueLimit = 5000; * * // Initialize the AsyncFlushTargetWrapper for the ConsoleWrapper * AutoFlushTargetWrapper consoleFlushWrapper = new AutoFlushTargetWrapper(); * consoleFlushWrapper.WrappedTarget = consoleWrapper; * * // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule * consoleFlushWrapper.Condition = "level >= LogLevel.Info"; * * // Adding the target to the config * config.AddTarget("console", consoleFlushWrapper); */ // Initialize File Target var fileTarget = new FileTarget("File Target") { FileName = @"${basedir}\logs\Robotics Automation Log.xml", DeleteOldFileOnStartup = true, // Deletes old log file every time log is called. Set to true simply for testing purposes KeepFileOpen = true, // Keeps file open regardless of logger status. (Increases performance) OpenFileCacheTimeout = 30, // Max number of seconds file is kept open. (Increases performance, but the value will scale with the scope of logger implementation) Layout = @"${IndentationLayout} ${date:format=yyyy-MM-dd HH\:mm\:ss} | ${level:uppercase=true} | ${message}" //use IndentationLayout }; //// XmlLayout Configuration //var XmlLayout = new XmlLayout(); //XmlLayout.IndentXml = true; //XmlLayout.ElementName = "Automated Test"; //XmlLayout.ElementValue = "Current Test"; // Unit Test name can be entered into here so each log entry will include Unit Test //XmlLayout.MaxRecursionLimit = 10; //XmlLayout.Attributes.Add(new XmlAttribute("Time", "${longdate}")); //XmlLayout.Attributes.Add(new XmlAttribute("Level", "${level:upperCase=true")); //XmlLayout.Elements.Add(new XmlElement("Output", "${message}")); //XmlLayout.Elements.Add(new XmlElement("Location", "${callsite:methodName=true}")); //fileTarget.Layout = XmlLayout; // Initialize the AsyncWrapper for the fileTarget AsyncTargetWrapper fileWrapper = new AsyncTargetWrapper(); fileWrapper.WrappedTarget = fileTarget; fileWrapper.QueueLimit = 5000; // Limits number of requests in the request queue (Improves performance) fileWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block; // Blocks incoming requests until request queue if has space // Initialize the AsyncFlushTargetWrapper for the FileWrapper AutoFlushTargetWrapper fileFlushWrapper = new AutoFlushTargetWrapper(); fileFlushWrapper.WrappedTarget = fileWrapper; /* * // Initiliaze Database Target * var dbTarget = new DatabaseTarget * { * ConnectionString = WhatINeed, * DBProvider = "MongoServer", * Name = "Mongo", * CommandText = * @"insert into dbo.Log ( * Logged, Level, Message, Username, Url, Logger, Callsite, Exception, Stacktrace, remoteAddress * ) values( * @Logged, @Level, @Message, @Username, @Url, @Logger, @Callsite, @Exception, @Stacktrace, @remoteAddress * );" * }; * * // Adding all database parameters to pass through Mongo * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Logged", "${date}")); * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Level", "${level}")); * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}")); * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Username", "${identity}")); * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Url", "${I need this}")); * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Logger", "${logger}")); * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Callsite", "${callsite}")); * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Exception", "${exception:format=toString}")); * dbTarget.Parameters.Add(new DatabaseParameterInfo("@StackTrace", "${stacktrace}")); * * // Add the target to the config * config.AddTarget("database", dbTarget); * * var databaseRule = new LoggingRule("DatabaseRule", LogLevel.Trace, dbTarget); * config.LoggingRules.Add(databaseRule); */ // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule fileFlushWrapper.Condition = "level >= LogLevel.Info"; // Adding the target to the config config.AddTarget("file", fileFlushWrapper); // Creating the Log Level rules for each target and adding them to the config var fileRule = new LoggingRule("*", fileTarget); fileRule.EnableLoggingForLevel(exceptionLevel); fileRule.EnableLoggingForLevels(minLevel, maxLevel); config.LoggingRules.Add(fileRule); /* * var consoleRule = new LoggingRule("*", consoleTarget); * consoleRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Info); * consoleRule.EnableLoggingForLevel(LogLevel.Error); * config.LoggingRules.Add(consoleRule); */ // Assigning the configuration to the logger LogManager.Configuration = config; }
public void ConfigureLogging() { // Intialize Config Object LoggingConfiguration config = new LoggingConfiguration(); // Initialize Console Target var consoleTarget = new ColoredConsoleTarget("Console Target") { Layout = @"${time} ${longdate} ${uppercase: ${level}} ${logger} ${message} ${exception: format=ToString}" }; // Initialize the AsyncWrapper for the ConsoleTarget AsyncTargetWrapper consoleWrapper = new AsyncTargetWrapper(); consoleWrapper.WrappedTarget = consoleTarget; consoleWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block; consoleWrapper.QueueLimit = 5000; // Initialize the AsyncFlushTargetWrapper for the ConsoleWrapper AutoFlushTargetWrapper consoleFlushWrapper = new AutoFlushTargetWrapper(); consoleFlushWrapper.WrappedTarget = consoleWrapper; // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule consoleFlushWrapper.Condition = "level >= LogLevel.Trace"; // Adding the target to the config config.AddTarget("console", consoleFlushWrapper); // Initialize File Target var fileTarget = new FileTarget("File Target") { FileName = "Logs\\${cached:cached=true:Inner=${date:format=dd.MM.yyyy HH-mm}:CacheKey=${shortdate}}.log", KeepFileOpen = false, Layout = @"[${date:format=dd.MM.yyyy HH-mm-ss}] ${message} ${exception: format=ToString}" }; // Initialize the AsyncWrapper for the fileTarget AsyncTargetWrapper fileWrapper = new AsyncTargetWrapper(); fileWrapper.WrappedTarget = fileTarget; fileWrapper.QueueLimit = 5000; fileWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block; // Initialize the AsyncFlushTargetWrapper for the FileWrapper AutoFlushTargetWrapper fileFlushWrapper = new AutoFlushTargetWrapper(); fileFlushWrapper.WrappedTarget = fileWrapper; // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule fileFlushWrapper.Condition = "level >= LogLevel.Trace"; // Adding the target to the config config.AddTarget("file", fileFlushWrapper); // Creating the Log Level rules for each target and adding them to the config // Edit these to change what methods are logged var fileRule = new LoggingRule("*", fileTarget); fileRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Info); fileRule.EnableLoggingForLevel(LogLevel.Error); config.LoggingRules.Add(fileRule); var consoleRule = new LoggingRule("*", consoleTarget); consoleRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Info); consoleRule.EnableLoggingForLevel(LogLevel.Error); config.LoggingRules.Add(consoleRule); // Assigning the configuration to the logger LogManager.Configuration = config; }
private static void Init() { LoggingConfiguration configuration = new LoggingConfiguration(); FileTarget target = new FileTarget(); configuration.AddTarget("file", target); target.FileName = LogPath + "${date:format=yyyyMMdd}/tracelog.txt"; target.Layout = "${date:format=HH\\:mm\\:ss}\t${message}\t${logger}\t${stacktrace}"; LoggingRule item = new LoggingRule("*", target); item.EnableLoggingForLevel(LogLevel.Trace); configuration.LoggingRules.Add(item); FileTarget target2 = new FileTarget(); configuration.AddTarget("file", target2); target2.FileName = LogPath + "${date:format=yyyyMMdd}/debuglog.txt"; target2.Layout = "${date:format=HH\\:mm\\:ss}\t${message}\t${logger}\t${stacktrace}"; LoggingRule rule2 = new LoggingRule("*", target2); rule2.EnableLoggingForLevel(LogLevel.Debug); configuration.LoggingRules.Add(rule2); FileTarget target3 = new FileTarget(); configuration.AddTarget("file", target3); target3.FileName = LogPath + "${date:format=yyyyMMdd}/infolog.txt"; target3.Layout = "${date:format=HH\\:mm\\:ss}\t${message}\t${logger}\t${stacktrace}"; LoggingRule rule3 = new LoggingRule("*", target3); rule3.EnableLoggingForLevel(LogLevel.Info); configuration.LoggingRules.Add(rule3); FileTarget target4 = new FileTarget(); configuration.AddTarget("file", target4); target4.FileName = LogPath + "${date:format=yyyyMMdd}/warnlog.txt"; target4.Layout = "${date:format=HH\\:mm\\:ss}\t${message}\t${logger}\t${stacktrace}"; LoggingRule rule4 = new LoggingRule("*", target4); rule4.EnableLoggingForLevel(LogLevel.Warn); configuration.LoggingRules.Add(rule4); FileTarget target5 = new FileTarget(); configuration.AddTarget("file", target5); target5.FileName = LogPath + "${date:format=yyyyMMdd}/errorlog.txt"; target5.Layout = "${date:format=HH\\:mm\\:ss}\t${message}\t${logger}\t${stacktrace}"; LoggingRule rule5 = new LoggingRule("*", target5); rule5.EnableLoggingForLevel(LogLevel.Error); configuration.LoggingRules.Add(rule5); FileTarget target6 = new FileTarget(); configuration.AddTarget("file", target6); target6.FileName = LogPath + "${date:format=yyyyMMdd}/fatallog.txt"; target6.Layout = "${date:format=HH\\:mm\\:ss}\t${message}\t${logger}\t${stacktrace}"; LoggingRule rule6 = new LoggingRule("*", target6); rule6.EnableLoggingForLevel(LogLevel.Fatal); configuration.LoggingRules.Add(rule6); LogManager.Configuration = configuration; }