mayho33
Goto Top

C-Sharp NLog verschiedene Layouts zur Laufzeit

Hi @ all,

Ich verwende in meinen Projekten NLog. Nun frage ich mich wie ich es anstellen kann, zur Laufzeit das FileTarget.Layout zu ändern.

Etwa bei einem LogFile das dann z.B. in etwa so aussehen soll (exemplarisch). Den LogLevel (Error, Warn, Info, usw) will ich aber nur bei den Punkten Executing und ExitCode um mit CMTrace.exe schnell die relevanten Teile finden zu können:
===========================================================================
Script started by       : Domain\User
Script Creator          : PackageAutor
Computername            : MYHostname
Operating System        : Microsoft Windows 10 Enterprise x64
OSBuild                 : 18363.815
OSVersion               : 10.x.x.x.x
OSRelease               : 1903
Starttime               : 2020.04.28 13:17:01
Package to Install      : Publisher DisplayName DisplayVersion
===========================================================================

=============================================================================
    2020.04.28 13:04:28 || First Step
=============================================================================
        executing       :  cmd.exe /c notepad.exe
        exitcode        :  0

=============================================================================
    2020.04.28 13:24:00 || another doing
=============================================================================
        executing       :  setup.exe /silent /norestart
        exitcode        :  0

=============================================================================
    2020.04.28 13:44:00 || further doing
=============================================================================
        executing       :  cmd.exe /c REG IMPORT "<path>"  
        exitcode        :  0

Hier meine NLog Class die ich nach Änderung übernehmen will:
partial class Logging
    {
        public static string logPath         = @"C:\Logs";  
        public static string logName         = "ResetNetwork.log";  
        public static string nLogLogFileName = Path.Combine(logPath, logName);
        public static Logger logger          = NLogConfig();

        public static NLog.Logger NLogConfig()
        {
            string logLayout_NORMAL = String.Format("{0} {1}/t||/t{2}",   
                                                    "${date:format=dd.MM.yyyy HH\\:mm\\:ss.fff}",  
                                                    "(${uppercase:${level}})",  
                                                    "${message} ${exception}");  

            LoggingConfiguration configFILE            = new LoggingConfiguration();
            ColoredConsoleTarget configCONSOLE         = new ColoredConsoleTarget("console")  
            {
                Layout = logLayout_NORMAL
            };

            foreach (var item in ConsoleColors())
            {
                configCONSOLE.RowHighlightingRules.Add(item);
            }


            FileTarget fileTarget = LogfileTarget(logLayout_NORMAL, "file");  
            configFILE.AddTarget("normal", fileTarget);  
            configFILE.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget));  

            configFILE.AddRuleForAllLevels(configCONSOLE);
            configFILE.AddTarget(configCONSOLE);

            LogManager.Configuration = configFILE;
            return LogManager.GetCurrentClassLogger();
        }


        internal static FileTarget LogfileTarget(string layout, string name)
        {
            FileTarget toReturn = new FileTarget
            {
                Encoding                = Encoding.UTF8,
                ArchiveOldFileOnStartup = true,
                ArchiveNumbering        = ArchiveNumberingMode.Date,
                ArchiveFileName         = nLogLogFileName,
                ArchiveDateFormat       = "yyyy.MM.dd HH.mm.ss",  
                ConcurrentWrites        = true,
                KeepFileOpen            = false,
                MaxArchiveFiles         = 10,
                FileName                = nLogLogFileName,
                CreateDirs              = true
            };
            toReturn.ArchiveFileName = Regex.Replace(nLogLogFileName, (Path.GetFileNameWithoutExtension(logName) + @"\.log"), (Path.GetFileNameWithoutExtension(logName) + " {#}.log"), RegexOptions.IgnoreCase);   
            toReturn.Layout          = layout;
            toReturn.Name            = name;

            return toReturn;
        }



        internal static List<ConsoleRowHighlightingRule> ConsoleColors()
        {
            List<ConsoleRowHighlightingRule> toReturn = new List<ConsoleRowHighlightingRule>();

            ConsoleRowHighlightingRule InfoColor = new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Info"),  
                ForegroundColor = ConsoleOutputColor.White
            };
            toReturn.Add(InfoColor);



            ConsoleRowHighlightingRule ErrorColor = new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Error"),  
                ForegroundColor = ConsoleOutputColor.Red
            };
            toReturn.Add(ErrorColor);


            ConsoleRowHighlightingRule DebugColor = new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Debug"),  
                ForegroundColor = ConsoleOutputColor.Green
            };
            toReturn.Add(DebugColor);


            ConsoleRowHighlightingRule WarnColor = new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Warn"),  
                ForegroundColor = ConsoleOutputColor.Yellow
            };
            toReturn.Add(WarnColor);


            ConsoleRowHighlightingRule TraceColor = new ConsoleRowHighlightingRule
            {
                Condition       = ConditionParser.ParseExpression("level == LogLevel.Trace"),  
                ForegroundColor = ConsoleOutputColor.Gray
            };
            toReturn.Add(TraceColor);

            return toReturn;
        }
    }

Für Tipps wäre ich sehr dankbar!

Grüße!

Mayho

Content-Key: 568095

Url: https://administrator.de/contentid/568095

Printed on: June 15, 2024 at 00:06 o'clock