/// <summary>
 /// Adds the elements of an array to the end of this ConsoleRowHighlightingRuleCollection.
 /// </summary>
 /// <param name="items">
 /// The array whose elements are to be added to the end of this ConsoleRowHighlightingRuleCollection.
 /// </param>
 public virtual void AddRange(ConsoleRowHighlightingRule[] items)
 {
     foreach (ConsoleRowHighlightingRule item in items)
     {
         this.List.Add(item);
     }
 }
Beispiel #2
0
        public static LoggingConfiguration GetConfig()
        {
            var config = new NLog.Config.LoggingConfiguration();

            //Targets where to log to: File and Console

            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = $"log/{DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString()}.txt"
            };
            var consoleTarget = new ColoredConsoleTarget();

            consoleTarget.Layout = "${date:format=HH\\:mm\\:ss} | ${callsite:className=true:includeNamespace=false:fileName=false:includeSourcePath=false:methodName=true} | [${level:uppercase=true}] : ${message}";

            var highlightRule = new ConsoleRowHighlightingRule();

            consoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule("[INFO]", ConsoleOutputColor.DarkBlue, ConsoleOutputColor.NoChange));
            consoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule("[Send]", ConsoleOutputColor.DarkMagenta, ConsoleOutputColor.NoChange));
            consoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule("[Receive]", ConsoleOutputColor.DarkCyan, ConsoleOutputColor.NoChange));
            consoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule("[DEBUG]", ConsoleOutputColor.DarkGreen, ConsoleOutputColor.NoChange));
            consoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule("[ERROR]", ConsoleOutputColor.DarkRed, ConsoleOutputColor.NoChange));

            //Rules for mapping loggers to targets
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, consoleTarget);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

            return(config);
        }
        public void InitLogger(string logFilenameSuffix)
        {
            LoggingConfiguration config        = new LoggingConfiguration();
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget
            {
                Name   = "console",
                Layout = "[${time} | ${level:format=FirstCharacter} | ${logger}] ${message}"
            };
            ConsoleRowHighlightingRule highlightRule = new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Info"),
                ForegroundColor = ConsoleOutputColor.Green
            };

            consoleTarget.RowHighlightingRules.Add(highlightRule);
            string     suffix     = string.IsNullOrEmpty(logFilenameSuffix) ? "" : $"_{logFilenameSuffix}";
            FileTarget fileTarget = new FileTarget
            {
                FileName = $"{LogsDirectory}/{typeof(TClass).Name}{suffix}.log",
                DeleteOldFileOnStartup = true,
                Layout = "[${time} | ${level:format=FirstCharacter} | ${logger}] ${message}"
            };

            config.AddRule(LogLevel.Trace, LogLevel.Fatal, consoleTarget);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget);
            LogManager.Configuration = config;
        }
Beispiel #4
0
        private static IEnumerable <ConsoleRowHighlightingRule> GetColorRules()
        {
            return(ColoringRules.Select(_ =>
            {
                var highlightRule = new ConsoleRowHighlightingRule();

                highlightRule.Condition = ConditionParser.ParseExpression(string.Format("level == LogLevel.{0}", _.Key.ToString()));
                highlightRule.ForegroundColor = _.Value;

                return highlightRule;
            }));
        }
Beispiel #5
0
        /// <summary>
        ///     Creates the console <see cref="NLog.Targets.Target">Target</see>.
        /// </summary>
        /// <param name="targetName">Name of the target.</param>
        /// <param name="rowHighlightingRule">The row highlighting rule.</param>
        /// <returns>A new target with the specified name.</returns>
        public ColoredConsoleTarget CreateConsoleTarget
            (string targetName, ConsoleRowHighlightingRule rowHighlightingRule)
        {
            var target = new ColoredConsoleTarget
                             (targetName)
            {
                DetectConsoleAvailable = true
                ,
                Encoding = Encoding.UTF8
                ,
                Layout = CreateTargetLayout()
                ,
                RowHighlightingRules = { rowHighlightingRule }
            };

            return(target);
        }
Beispiel #6
0
        /// <summary>
        ///     Initialize logger's configuration.
        ///     Please refer to https://github.com/nlog/NLog/wiki/Layout-Renderers for custom layouts.
        /// </summary>
        /// <param name="consoleLayout"></param>
        /// <param name="fileLayout"></param>
        public static void Initialize(string consoleLayout, string fileLayout)
        {
            var config        = new LoggingConfiguration();
            var consoleTarget = new ColoredConsoleTarget();
            var fileTarget    = new FileTarget();

            consoleTarget.Layout = consoleLayout;

            var infoHighlightRule = new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Info"),
                ForegroundColor = ConsoleOutputColor.Green
            };
            var errorHighlightRule = new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Error"),
                ForegroundColor = ConsoleOutputColor.Red
            };
            var warnHighlightingRule = new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Warn"),
                ForegroundColor = ConsoleOutputColor.DarkYellow
            };

            consoleTarget.RowHighlightingRules.Add(infoHighlightRule);
            consoleTarget.RowHighlightingRules.Add(errorHighlightRule);
            consoleTarget.RowHighlightingRules.Add(warnHighlightingRule);

            fileTarget.Layout   = fileLayout;
            fileTarget.FileName = "logs/" + DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss") + ".log";

            config.AddTarget("console", consoleTarget);
            config.AddTarget("file", fileTarget);

            var rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);

            config.LoggingRules.Add(rule1);

            var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);

            config.LoggingRules.Add(rule2);

            LogManager.Configuration = config;
        }
        public LogConfigBuilder AddColoredConsoleAppender(LogLevel logLevel = null, string layout = DefaultConsoleLayout)
        {
            var consoleTarget = new ColoredConsoleTarget
            {
                Layout = layout
            };

            var highlightRule = new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Debug"),
                ForegroundColor = ConsoleOutputColor.DarkGray
            };

            consoleTarget.RowHighlightingRules.Add(highlightRule);

            _loggingConfiguration.AddTarget("console", consoleTarget);
            _loggingConfiguration.LoggingRules.Add(new LoggingRule("*", logLevel ?? LogLevel.Debug, consoleTarget));

            return(this);
        }
Beispiel #8
0
        private static void SetLogging(string?logfile)
        {
            var config = new NLog.Config.LoggingConfiguration();

            Target logfileTarget = null;

            if (!string.IsNullOrEmpty(logfile) && File.Exists(logfile))
            {
                logfileTarget = new FileTarget("logfile")
                {
                    FileName = logfile
                }
            }
            ;
#if DEBUG
            if (logfileTarget != null)
            {
                config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfileTarget);
            }
            var consoleTarget = new ColoredConsoleTarget();
            var highlightRule = new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Info"),
                ForegroundColor = ConsoleOutputColor.Green
            };
            consoleTarget.RowHighlightingRules.Add(highlightRule);

            config.AddRule(LogLevel.Trace, LogLevel.Fatal, consoleTarget);
#else
            if (logfileTarget != null)
            {
                config.AddRule(LogLevel.Info, LogLevel.Fatal, logfileTarget);
            }
#endif
            LogManager.Configuration = config;
        }
Beispiel #9
0
        public PhantomLogger(LoggerModule module)
        {
            var loggerConfig = new LoggingConfiguration();

            var consoleTarget = new ColoredConsoleTarget("PhantomConsoleTarget");

            // Console log layout
            consoleTarget.Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss} | ${logger} ${level} - ${message}  ${exception}";

            // Replaces the Info log color to Green
            var infoGreenRule = new ConsoleRowHighlightingRule();

            infoGreenRule.Condition       = ConditionParser.ParseExpression("level == LogLevel.Info");
            infoGreenRule.ForegroundColor = ConsoleOutputColor.Green;

            consoleTarget.RowHighlightingRules.Add(infoGreenRule);

            // Add targets and rules
            loggerConfig.AddTarget(consoleTarget);
            loggerConfig.AddRuleForAllLevels(consoleTarget);

            LogManager.Configuration = loggerConfig;
            logger = LogManager.GetLogger(module.ToString());
        }
Beispiel #10
0
        internal void SetupLogger()
        {
            try
            {
                var logConfig     = new LoggingConfiguration();
                var consoleTarget = new ColoredConsoleTarget();
                var fileTarget    = new FileTarget();

                var highlightRuleInfo = new ConsoleRowHighlightingRule
                {
                    Condition       = ConditionParser.ParseExpression("level == LogLevel.Info"),
                    ForegroundColor = ConsoleOutputColor.DarkGreen
                };

                consoleTarget.RowHighlightingRules.Add(highlightRuleInfo);

                consoleTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger:shortName=true} | ${level:uppercase=true:padding=-5} | ${message}";
                fileTarget.FileName  = Path.Combine(_logDirectory, $"{DateTime.UtcNow.ToString("yyyy-MM-dd")}.log");
                fileTarget.Layout    = @"${date:format=HH\:mm\:ss} ${logger:shortName=true} | ${level:uppercase=true:padding=-5} | ${message}";

                logConfig.AddTarget("console", consoleTarget);
                logConfig.AddTarget("file", fileTarget);

                var rule1 = new LoggingRule("*", NLog.LogLevel.Info, consoleTarget);
                logConfig.LoggingRules.Add(rule1);

                var rule2 = new LoggingRule("*", NLog.LogLevel.Info, fileTarget);
                logConfig.LoggingRules.Add(rule2);

                LogManager.Configuration = logConfig;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
 /// <summary>
 /// Inserts an element into the ConsoleRowHighlightingRuleCollection at the specified index
 /// </summary>
 /// <param name="index">
 /// The index at which the ConsoleRowHighlightingRule is to be inserted.
 /// </param>
 /// <param name="value">
 /// The ConsoleRowHighlightingRule to insert.
 /// </param>
 public virtual void Insert(int index, ConsoleRowHighlightingRule value)
 {
     this.List.Insert(index, value);
 }
Beispiel #12
0
        /// <summary>
        /// Setup all the logging targets and rules. Call only once, usually at the start of the program.
        /// </summary>
        public static void Initialize()
        {
            Directory.CreateDirectory(Constants.LogDirectory);
            LoggingConfiguration loggingConfiguration = new LoggingConfiguration();

            // Setup and layout formatting for the console
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget()
            {
                Name = Constants.ApplicationName,
                //Layout = "${message}"
                // Match the console target format with file targets. It looks cluttered on small terminals
                Layout = "${longdate} [${pad:padCharacter= :padding=5:fixedLength=true:alignmentOnTruncation=Right:${uppercase:${level}}}] [${callsite:includeNamespace=false:cleanNamesOfAnonymousDelegates=true:cleanNamesOfAsyncContinuations=true}] ${message}"
            };

            // Override the trace color
            ConsoleRowHighlightingRule consoleTarget_RowRules_Trace = new ConsoleRowHighlightingRule()
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Trace"),
                ForegroundColor = ConsoleOutputColor.Gray
            };

            consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Trace);

            // Override the debug color
            ConsoleRowHighlightingRule consoleTarget_RowRules_Debug = new ConsoleRowHighlightingRule()
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Debug"),
                ForegroundColor = ConsoleOutputColor.Gray
            };

            consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Debug);

            // Override the info color
            ConsoleRowHighlightingRule consoleTarget_RowRules_Info = new ConsoleRowHighlightingRule()
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Info"),
                ForegroundColor = ConsoleOutputColor.White
            };

            consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Info);

            // Override the warn color
            ConsoleRowHighlightingRule consoleTarget_RowRules_Warn = new ConsoleRowHighlightingRule()
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Warn"),
                ForegroundColor = ConsoleOutputColor.Yellow
            };

            consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Warn);

            // Override the error color
            ConsoleRowHighlightingRule consoleTarget_RowRules_Error = new ConsoleRowHighlightingRule()
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Error"),
                ForegroundColor = ConsoleOutputColor.Red
            };

            consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Error);

            // Override the fatal color
            ConsoleRowHighlightingRule consoleTarget_RowRules_Fatal = new ConsoleRowHighlightingRule()
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Fatal"),
                ForegroundColor = ConsoleOutputColor.Red
            };

            consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Fatal);

            // Add consoleTarget to the overall configuration
            loggingConfiguration.AddTarget(consoleTarget);
            loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Fatal, Constants.ApplicationName);

            // =================================

            // All messages from Trace to Warn levels write to the general file
            FileTarget fileTarget_General = new FileTarget()
            {
                Name             = Constants.ApplicationName,
                FileName         = Path.Combine(Constants.LogDirectory, "General.log"),
                Layout           = "${longdate} [${pad:padCharacter= :padding=5:fixedLength=true:alignmentOnTruncation=Right:${uppercase:${level}}}] [${callsite:includeNamespace=false:cleanNamesOfAnonymousDelegates=true:cleanNamesOfAsyncContinuations=true}] ${message}",
                ArchiveFileName  = Path.Combine(Constants.LogDirectory, "General{#}.Archive.log"),
                ArchiveEvery     = FileArchivePeriod.Day,
                ArchiveNumbering = ArchiveNumberingMode.Rolling,
                MaxArchiveFiles  = 7,
                ConcurrentWrites = false
            };
            // Limit how often the file will get written to disk.
            // Default: BufferSize = 50 (log events), FlushTimeout = 5000 (milliseconds)
            BufferingTargetWrapper fileAsyncTargetWrapper_General = new BufferingTargetWrapper {
                Name           = Constants.ApplicationName,
                WrappedTarget  = fileTarget_General,
                BufferSize     = 50,
                FlushTimeout   = 5000,
                SlidingTimeout = false
            };

            loggingConfiguration.AddTarget(fileAsyncTargetWrapper_General);
            loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Warn, Constants.ApplicationName);

            // All messages from Warn to Fatal levels write to the error file with advanced trace information
            FileTarget fileTarget_Error = new FileTarget()
            {
                Name             = Constants.ApplicationName,
                FileName         = Path.Combine(Constants.LogDirectory, "Error.log"),
                Layout           = "${longdate} [${pad:padCharacter= :padding=5:fixedLength=true:alignmentOnTruncation=Right:${uppercase:${level}}}] [${callsite:includeSourcePath=true:cleanNamesOfAnonymousDelegates=true:cleanNamesOfAsyncContinuations=true}:${callsite-linenumber}; ${stacktrace}] ${message}${exception:format=ToString,StackTrace}",
                ArchiveFileName  = Path.Combine(Constants.LogDirectory, "Error{#}.Archive.log"),
                ArchiveEvery     = FileArchivePeriod.Day,
                ArchiveNumbering = ArchiveNumberingMode.Rolling,
                MaxArchiveFiles  = 7,
                ConcurrentWrites = false
            };

            loggingConfiguration.AddTarget(fileTarget_Error);
            loggingConfiguration.AddRule(LogLevel.Error, LogLevel.Fatal, Constants.ApplicationName);

            // Apply all the custom configurations to the LogManager
            LogManager.Configuration = loggingConfiguration;

            Log.Info("Logging initialization finished.");
        }
 /// <summary>
 /// Adds an instance of type ConsoleRowHighlightingRule to the end of this ConsoleRowHighlightingRuleCollection.
 /// </summary>
 /// <param name="value">
 /// The ConsoleRowHighlightingRule to be added to the end of this ConsoleRowHighlightingRuleCollection.
 /// </param>
 public virtual void Add(ConsoleRowHighlightingRule value)
 {
     this.List.Add(value);
 }
 /// <summary>
 /// Determines whether a specfic ConsoleRowHighlightingRule value is in this ConsoleRowHighlightingRuleCollection.
 /// </summary>
 /// <param name="value">
 /// The ConsoleRowHighlightingRule value to locate in this ConsoleRowHighlightingRuleCollection.
 /// </param>
 /// <returns>
 /// true if value is found in this ConsoleRowHighlightingRuleCollection;
 /// false otherwise.
 /// </returns>
 public virtual bool Contains(ConsoleRowHighlightingRule value)
 {
     return this.List.Contains(value);
 }
 /// <summary>
 /// Return the zero-based index of the first occurrence of a specific value
 /// in this ConsoleRowHighlightingRuleCollection
 /// </summary>
 /// <param name="value">
 /// The ConsoleRowHighlightingRule value to locate in the ConsoleRowHighlightingRuleCollection.
 /// </param>
 /// <returns>
 /// The zero-based index of the first occurrence of the _ELEMENT value if found;
 /// -1 otherwise.
 /// </returns>
 public virtual int IndexOf(ConsoleRowHighlightingRule value)
 {
     return this.List.IndexOf(value);
 }
 /// <summary>
 /// Initializes a new instance of the ConsoleRowHighlightingRuleCollection class, containing elements
 /// copied from an array.
 /// </summary>
 /// <param name="items">
 /// The array whose elements are to be added to the new ConsoleRowHighlightingRuleCollection.
 /// </param>
 public ConsoleRowHighlightingRuleCollection(ConsoleRowHighlightingRule[] items)
 {
     this.AddRange(items);
 }
 /// <summary>
 /// Removes the first occurrence of a specific ConsoleRowHighlightingRule from this ConsoleRowHighlightingRuleCollection.
 /// </summary>
 /// <param name="value">
 /// The ConsoleRowHighlightingRule value to remove from this ConsoleRowHighlightingRuleCollection.
 /// </param>
 public virtual void Remove(ConsoleRowHighlightingRule value)
 {
     this.List.Remove(value);
 }