public static LoggingConfiguration UseElastic(this LoggingConfiguration configuration, LogConfig config)
        {
            if (!string.IsNullOrEmpty(config.Elastic?.Uri))
            {
                if (config.HostName.Contains("-"))
                {
                    throw new InvalidOperationException($"Dash character (-) is not allowed in the Logging.HostName property. Please check your application settings file.");
                }

                var target = new ElasticSearchTarget
                {
                    Name        = "Elastic",
                    CloudId     = config.Elastic.CloudId,
                    Username    = config.Elastic.Username,
                    Password    = config.Elastic.Password,
                    RequireAuth = true,
                    Uri         = config.Elastic.Uri,
                    Index       = $"logs-{config.HostName}",
                    Fields      = new List <Field>
                    {
                        new Field {
                            Name = "host.name", Layout = config.HostName
                        },
                        new Field {
                            Name = "application", Layout = config.ApplicationName
                        }
                    },
                    Layout = "${message}"
                };

                configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.FromString(config.Elastic.LogLevel ?? "Trace"), target));
            }

            return(configuration);
        }
Example #2
0
        public void SetLogLevel(string logLevel)
        {
            var level = LogLevel.FromString(logLevel);

            if (level == LogLevel.Off)
            {
                LogManager.DisableLogging();
            }
            else
            {
                if (!LogManager.IsLoggingEnabled())
                {
                    LogManager.EnableLogging();
                }
                foreach (var rule in LogManager.Configuration.LoggingRules)
                {
                    rule.DisableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal);
                    // Iterate over all levels up to and including the target, (re)enabling them.
                    for (var i = level.Ordinal; i <= 5; i++)
                    {
                        rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
                    }
                }
            }

            LogManager.ReconfigExistingLoggers();
        }
        public static LoggingConfiguration UsePaperTrail(this LoggingConfiguration configuration, LogConfig config)
        {
            if (!string.IsNullOrEmpty(config.Papertrail?.Server))
            {
                var syslogTarget = new SyslogTarget
                {
                    Name            = "PaperTrail",
                    MessageCreation = new MessageBuilderConfig
                    {
                        Facility = Facility.Local7,
                        Rfc5424  = new Rfc5424Config
                        {
                            AppName  = config.ApplicationName,
                            Hostname = config.HostName ?? Environment.MachineName,
                        },
                    },
                    MessageSend = new MessageTransmitterConfig
                    {
                        Protocol = ProtocolType.Tcp,
                        Tcp      = new TcpConfig
                        {
                            Server = config.Papertrail.Server,
                            Port   = config.Papertrail.Port,
                            Tls    = new TlsConfig
                            {
                                Enabled = true,
                            },
                        },
                    },
                };

                configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.FromString(config.Papertrail.LogLevel ?? "Trace"), syslogTarget));
            }
            return(configuration);
        }
Example #4
0
        public static NLogLoggingConfiguration UseMongoTarget(this NLogLoggingConfiguration nlogConf, IConfiguration configuration)
        {
            var targetOption = configuration.GetSection(nameof(NLogNoSqlTargetOptions)).Get <NLogNoSqlTargetOptions>();
            var mongoOption  = configuration.GetSection(nameof(LogStorageOptions)).Get <LogStorageOptions>();

            if (targetOption == null || mongoOption == null)
            {
                throw new NullReferenceException($"Cannot found {nameof(NLogNoSqlTargetOptions)} or {nameof(LogStorageOptions)} from configuration file!");
            }

            var mongoTarget = new MongoTarget()
            {
                Name             = targetOption.Name,
                CollectionName   = targetOption.CollectionName,
                ConnectionString = configuration["MongoDBConnection"],
                DatabaseName     = mongoOption.DatabaseName,
                IncludeDefaults  = true
            };

            nlogConf.AddTarget(mongoTarget);

            foreach (var r in targetOption.Rules)
            {
                var minlevel = LogLevel.FromString(r.MinLevel);
                var maxLevel = LogLevel.FromString(r.MaxLevel);
                nlogConf.AddRule(minlevel, maxLevel, mongoTarget, r.Logger);
            }

            return(nlogConf);
        }
        public static LoggingConfiguration UseConsole(this LoggingConfiguration config, LogConfig configuration)
        {
            if (!string.IsNullOrEmpty(configuration.ConsoleLogLevel))
            {
                var target = new ConsoleTarget("Console");
                config.LoggingRules.Add(new LoggingRule("*", LogLevel.FromString(configuration.ConsoleLogLevel ?? "Trace"), target));
            }

            return(config);
        }
        public static LoggingConfiguration UseFile(this LoggingConfiguration config, LogConfig fileTelemetryConfig)
        {
            if (!string.IsNullOrEmpty(fileTelemetryConfig.FileLogLevel))
            {
                config.LoggingRules.Add(new LoggingRule("*", LogLevel.FromString(fileTelemetryConfig.FileLogLevel), new FileTarget()
                {
                    Name = "File", Layout = "${longdate} ${logger} ${message}", FileName = "${basedir}/logs/${shortdate}.log"
                }));
            }

            return(config);
        }
Example #7
0
        private void LogLevelSelectionChangedHandler(object aSender, SelectionChangedEventArgs aEvent)
        {
            var c     = LogManager.Configuration;
            var level = ((ComboBoxItem)LogLevelComboBox.SelectedValue).Content.ToString();

            try
            {
                c.LoggingRules.Remove(_outgoingLoggingRule);
                _outgoingLoggingRule = new LoggingRule("*", LogLevel.FromString(level), _logTarget);
                c.LoggingRules.Add(_outgoingLoggingRule);
                LogManager.Configuration = c;
            }
            catch (ArgumentException)
            {
                LogManager.GetCurrentClassLogger().Error($"Log Level \"{level}\" is not a valid log level!");
            }
        }
        public static LoggingConfiguration UseSlack(this LoggingConfiguration config, LogConfig configuration)
        {
            if (!string.IsNullOrEmpty(configuration.Slack?.TelemetryKey))
            {
                var slackTarget = new SlackTarget
                {
                    Layout     = "${message}",
                    WebHookUrl = "https://hooks.slack.com/services/" + configuration.Slack.TelemetryKey,
                    Channel    = configuration.Slack.Channel,
                    Username   = configuration.ApplicationName,
                    Compact    = true
                };

                config.LoggingRules.Add(new LoggingRule("*", LogLevel.FromString(configuration.Slack.LogLevel ?? "Warn"), slackTarget));
            }

            return(config);
        }
        private void InitAttributes()
        {
            if (!_attributesLoaded)
            {
                _attributesLoaded = true;

                if (Trace.AutoFlush)
                {
                    // Avoid a world of hurt, by not constantly spawning new flush threads
                    // Also timeout exceptions thrown by Flush() will not break diagnostic Trace-logic
                    _disableFlush = true;
                }

                foreach (DictionaryEntry de in Attributes)
                {
                    var key   = (string)de.Key;
                    var value = (string)de.Value;

                    switch (key.ToUpperInvariant())
                    {
                    case "DEFAULTLOGLEVEL":
                        _defaultLogLevel = LogLevel.FromString(value);
                        break;

                    case "FORCELOGLEVEL":
                        _forceLogLevel = LogLevel.FromString(value);
                        break;

                    case "AUTOLOGGERNAME":
                        AutoLoggerName = XmlConvert.ToBoolean(value);
                        break;

                    case "DISABLEFLUSH":
                        _disableFlush = bool.Parse(value);
                        break;
                    }
                }
            }
        }
Example #10
0
        internal static void ConfigureLogging()
        {
            var config        = Pool.clusterConfig.Logging;
            var loggingConfig = new LoggingConfiguration();

            if (config != null)
            {
                // parse level
                var level = !string.IsNullOrEmpty(config.Level)
                    ? LogLevel.FromString(config.Level)
                    : LogLevel.Info;

                var layout = "[${longdate}] [${level:format=FirstCharacter:uppercase=true}] [${logger:shortName=true}] ${message} ${exception:format=ToString,StackTrace}";

                var nullTarget = new NullTarget("null")
                {
                };

                loggingConfig.AddTarget(nullTarget);

                // Suppress some Aspnet stuff
                loggingConfig.AddRule(level, LogLevel.Info, nullTarget, "Microsoft.AspNetCore.Mvc.Internal.*", true);
                loggingConfig.AddRule(level, LogLevel.Info, nullTarget, "Microsoft.AspNetCore.Mvc.Infrastructure.*", true);

                // Api Log
                if (!string.IsNullOrEmpty(config.ApiLogFile))
                {
                    var target = new FileTarget("file")
                    {
                        FileName     = GetLogPath(config, config.ApiLogFile),
                        FileNameKind = FilePathKind.Unknown,
                        Layout       = layout
                    };

                    loggingConfig.AddTarget(target);
                    loggingConfig.AddRule(level, LogLevel.Fatal, target, "Microsoft.AspNetCore.*", true);
                }

                if (config.EnableConsoleLog)
                {
                    if (config.EnableConsoleColors)
                    {
                        var target = new ColoredConsoleTarget("console")
                        {
                            Layout = layout
                        };

                        target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule(
                                                            ConditionParser.ParseExpression("level == LogLevel.Trace"),
                                                            ConsoleOutputColor.DarkMagenta, ConsoleOutputColor.NoChange));

                        target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule(
                                                            ConditionParser.ParseExpression("level == LogLevel.Debug"),
                                                            ConsoleOutputColor.Gray, ConsoleOutputColor.NoChange));

                        target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule(
                                                            ConditionParser.ParseExpression("level == LogLevel.Info"),
                                                            ConsoleOutputColor.White, ConsoleOutputColor.NoChange));

                        target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule(
                                                            ConditionParser.ParseExpression("level == LogLevel.Warn"),
                                                            ConsoleOutputColor.Yellow, ConsoleOutputColor.NoChange));

                        target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule(
                                                            ConditionParser.ParseExpression("level == LogLevel.Error"),
                                                            ConsoleOutputColor.Red, ConsoleOutputColor.NoChange));

                        target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule(
                                                            ConditionParser.ParseExpression("level == LogLevel.Fatal"),
                                                            ConsoleOutputColor.DarkRed, ConsoleOutputColor.White));

                        loggingConfig.AddTarget(target);
                        loggingConfig.AddRule(level, LogLevel.Fatal, target);
                    }

                    else
                    {
                        var target = new ConsoleTarget("console")
                        {
                            Layout = layout
                        };

                        loggingConfig.AddTarget(target);
                        loggingConfig.AddRule(level, LogLevel.Fatal, target);
                    }
                }

                if (!string.IsNullOrEmpty(config.LogFile))
                {
                    var target = new FileTarget("file")
                    {
                        FileName     = GetLogPath(config, config.LogFile),
                        FileNameKind = FilePathKind.Unknown,
                        Layout       = layout
                    };

                    loggingConfig.AddTarget(target);
                    loggingConfig.AddRule(level, LogLevel.Fatal, target);
                }

                if (config.PerPoolLogFile)
                {
                    foreach (var poolConfig in Pool.clusterConfig.Pools)
                    {
                        var target = new FileTarget(poolConfig.Id)
                        {
                            FileName     = GetLogPath(config, poolConfig.Id + ".log"),
                            FileNameKind = FilePathKind.Unknown,
                            Layout       = layout
                        };

                        loggingConfig.AddTarget(target);
                        loggingConfig.AddRule(level, LogLevel.Fatal, target, poolConfig.Id);
                    }
                }
            }

            LogManager.Configuration = loggingConfig;

            // Set default logger name
            logger = LogManager.GetLogger("FileLogger");
        }
 private static LogLevel GetMinLogLevel() => LogLevel.FromString("Info");