예제 #1
0
        private void ReplaceNLogConsoleLogger(ConsoleTarget consoleTarget)
        {
            // Construct new methodCall target.
            MethodCallTarget methodCallTarget = new MethodCallTarget();

            methodCallTarget.ClassName  = typeof(TerminalPluginInitializer).AssemblyQualifiedName;
            methodCallTarget.MethodName = "RedirectLogMessage";
            methodCallTarget.Parameters.Add(new MethodCallParameter(consoleTarget.Layout));

            // Add new methodCall target into the configuration.
            LogManager.Configuration.AddTarget("terminalLogger", methodCallTarget);

            // Reconfigure the logging rules using console target to use new methodCall target.
            foreach (LoggingRule rule in LogManager.Configuration.LoggingRules)
            {
                if (rule.Targets.Contains(consoleTarget))
                {
                    rule.Targets.Remove(consoleTarget);
                    rule.Targets.Add(methodCallTarget);
                }
            }

            // Reconfigure existing loggers.
            LogManager.ReconfigExistingLoggers();
        }
예제 #2
0
        static CreekController()
        {
            MethodCallTarget target = new MethodCallTarget();
            // Log only the message from the same assembly of the class belongs to!!
            LoggingRule rule = new LoggingRule(
                typeof(CreekController).Assembly.GetName().Name + ".*",
                NLog.LogLevel.Error,
                target);

            // Initialize and add the MethodCallTarget to the NLog engine
            target.ClassName  = typeof(CreekController).AssemblyQualifiedName;
            target.MethodName = "LogError";
            target.Parameters.Add(new MethodCallParameter("level", typeof(string), "${level}"));
            target.Parameters.Add(new MethodCallParameter("message", typeof(string), "${message}"));
            if (File.Exists("NLog.config"))
            {
                // Read the settings from NLog.config and add the new target & rule
                XmlLoggingConfiguration oConfig = new XmlLoggingConfiguration("NLog.config");
                oConfig.AddTarget("MemoryTarget", target);
                oConfig.LoggingRules.Add(rule);
                NLog.LogManager.Configuration = oConfig;
            }
            else
            {
                throw new ApplicationException(AppResource.NLogConfigNotFound);
            }
        }
예제 #3
0
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();

        ChangeGui();

        logTextView = messages;

        var config = new LoggingConfiguration();
        MethodCallTarget target = new MethodCallTarget();

        target.ClassName  = typeof(MainWindow).AssemblyQualifiedName;
        target.MethodName = "LogMethod";
        target.Parameters.Add(new MethodCallParameter("${level}"));
        target.Parameters.Add(new MethodCallParameter("${message}"));
        target.Parameters.Add(new MethodCallParameter("${exception:format=tostring}"));
        config.AddTarget("gui", target);
        config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, target));
        LogManager.Configuration = config;

        messages.SizeAllocated += new SizeAllocatedHandler(ScrollMessages);

        messages.Buffer.TagTable.Add(tag_error = new TextTag("error")
        {
            Foreground = "#ff0000"
        });
        messages.Buffer.TagTable.Add(tag_warning = new TextTag("warning")
        {
            Foreground = "#B26B70"
        });
        messages.Buffer.TagTable.Add(tag_info = new TextTag("info")
        {
            Foreground = "#0000ff"
        });
    }
예제 #4
0
        public static IHostBuilder ConfigureNLog(this IHostBuilder hostBuilder)
        {
            var target = new MethodCallTarget(nameof(App.Log), App.Log);

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
            hostBuilder.ConfigureLogging(logging => logging.AddNLog());

            return(hostBuilder);
        }
예제 #5
0
        private static void InitListenerMethod()
        {
            MethodCallTarget target = new MethodCallTarget();

            target.ClassName  = typeof(LogListener).AssemblyQualifiedName;
            target.MethodName = "OnNewLogWrite";
            target.Parameters.Add(new MethodCallParameter("${level}"));
            target.Parameters.Add(new MethodCallParameter("${message}"));
            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, NLog.LogLevel.Debug);
        }
예제 #6
0
        /// <summary>
        /// Configure logger by MethodCallTarget
        /// </summary>
        /// <param name="target"></param>
        public void configure(MethodCallTarget target)
        {
            this.target = target;

            lock (_lock)
            {
                LogManager.ConfigurationChanged -= onCfgLoggerChanged;
                LogManager.ConfigurationChanged += onCfgLoggerChanged;
                initLoggerCfg();
            }

            Log.Trace(String.Format("Log('{0}') is configured for: '{1}'", target.ClassName, GuidList.PACKAGE_LOGGER));
        }
예제 #7
0
        /// <summary>
        /// Configure logger by default.
        /// </summary>
        public void configure()
        {
            var t = new MethodCallTarget()
            {
                ClassName  = typeof(Log).AssemblyQualifiedName,
                MethodName = "nprint"
            };

            t.Parameters.Add(new MethodCallParameter("${level:uppercase=true}"));
            t.Parameters.Add(new MethodCallParameter("${message}"));
            t.Parameters.Add(new MethodCallParameter("${ticks}"));

            configure(t);
        }
예제 #8
0
        private static void ConfigureNLog()
        {
            MethodCallTarget target = new MethodCallTarget();

            target.ClassName  = typeof(Program).AssemblyQualifiedName;
            target.MethodName = "LogMethod";
            target.Parameters.Add(new MethodCallParameter("${level}"));
            target.Parameters.Add(new MethodCallParameter("${message}"));
            target.Parameters.Add(new MethodCallParameter("${exception:format=tostring,Data:maxInnerExceptionLevel=10}"));
            target.Parameters.Add(new MethodCallParameter("${stacktrace}"));
            target.Parameters.Add(new MethodCallParameter("${callsite}"));

            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
        }
예제 #9
0
        public InstallServices()
        {
            InitializeComponent();

            MethodCallTarget target = new MethodCallTarget("MyTarget", (logEvent, parms) => InstallServicesLoggerClass.Logs.Add(new LogItem()
            {
                Level = logEvent.Level.ToString(), Message = logEvent.Message
            }));

            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
            logger.Info("log message");


            LbLogs.ItemsSource = InstallServicesLoggerClass.Logs;
        }
예제 #10
0
파일: Example.cs 프로젝트: ssavarala/nhin-d
    static void Main(string[] args)
    {
        MethodCallTarget target = new MethodCallTarget();

        target.ClassName  = typeof(Example).AssemblyQualifiedName;
        target.MethodName = "LogMethod";
        target.Parameters.Add(new MethodCallParameter("${level}"));
        target.Parameters.Add(new MethodCallParameter("${message}"));

        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);

        Logger logger = LogManager.GetLogger("Example");

        logger.Debug("log message");
        logger.Error("error message");
    }
예제 #11
0
        public LogBuilderTests()
        {
            var configuration = new LoggingConfiguration();

            var t1 = new MethodCallTarget("t1", (l, parms) => _lastLogEventInfo = l);
            var t2 = new DebugTarget {
                Name = "t2", Layout = "${message}"
            };

            configuration.AddTarget(t1);
            configuration.AddTarget(t2);
            configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t1));
            configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t2));

            LogManager.Configuration = configuration;
        }
예제 #12
0
        public void Initialize(string wbName, string context, bool createNew, string minLogLevel, bool autoShow)
        {
            if (Initialized)
            {
                throw new InvalidOperationException("Already initialized.");
            }

            if (String.IsNullOrWhiteSpace(wbName))
            {
                throw new ArgumentException("Invalid Workbook.Name.");
            }
            wbName  = wbName.Trim();
            context = context?.Trim();

            try {
                var config   = GetConfig();
                var loggerId = GetLoggerId(wbName, context);

                rule = config.FindRuleByName(loggerId);
                if (rule != null)
                {
                    if (!createNew)
                    {
                        mcp    = ((MethodCallTarget)config.FindTargetByName(loggerId)).Parameters[0];
                        logger = GetLogger(loggerId, wbName, context);
                        return;
                    }

                    config.RemoveRuleByName(loggerId);
                    config.RemoveTarget(loggerId);
                }

                var target = new MethodCallTarget(loggerId)
                {
                    ClassName  = typeof(ExcelDna.Logging.LogDisplay).AssemblyQualifiedName,
                    MethodName = autoShow ? "SetText" : "RecordMessage",
                    Parameters = { new MethodCallParameter(Configuration.DisplayLoggerLayout) }
                };
                mcp = target.Parameters[0];

                ConfigLogger(loggerId, wbName, context, target, minLogLevel);
            }
            catch (Exception ex) {
                ilogger.Error(ex, "Internal error");
                throw new InvalidOperationException(ex.Message);
            }
        }
예제 #13
0
        public static void Initialize(bool debugLog)
        {
            // final bet to be WinNT
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                throw new InvalidOperationException("Can not initialize windowed logger on non-Windows platforms.");
            }

            FreeConsole();

            // create an event, start the thread, and wait for the thread to initialize
            ms_waitEvent = new ManualResetEvent(false);
            new Thread(UIThread).Start();

            ms_waitEvent.WaitOne();

            // initialize a logger for the thread
            var config = new LoggingConfiguration();

            var target = new MethodCallTarget();

            target.ClassName  = typeof(WindowedLogger).AssemblyQualifiedName;
            target.MethodName = "LogOne";

            string outputFormat;

            if (!debugLog)
            {
                outputFormat = "${level}: ${message}";
            }
            else
            {
                outputFormat = "${mdc:item=sourceFile}(${mdc:item=sourceLine}): ${level}: ${mdc:item=typeName}::${mdc:item=memberName}: ${message}";
            }
            target.Parameters.Add(new MethodCallParameter(outputFormat));

            //NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Info);
            config.AddTarget("window", target);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, target));

            LogManager.Configuration   = config;
            LogManager.ThrowExceptions = true;

            // and dispose the wait event
            ms_waitEvent.Dispose();
        }
예제 #14
0
        public static void TryInitNLog()
        {
            if (LogManager.Configuration == null)
            {
                LoggingConfiguration LogConfig = new LoggingConfiguration();

                //status icon warning/errors
                MethodCallTarget StatusIconTarget = new MethodCallTarget();
                StatusIconTarget.ClassName  = typeof(LzsLogging).AssemblyQualifiedName;
                StatusIconTarget.MethodName = "LogWarningOrError";
                StatusIconTarget.Parameters.Add(new MethodCallParameter("${level}"));
                LoggingRule StatusIconRule = new LoggingRule("*", LogLevel.Warn, StatusIconTarget);
                LogConfig.AddTarget("StatusIcon", StatusIconTarget);
                LogConfig.LoggingRules.Add(StatusIconRule);

                //File log
                FileTarget LogFileTarget = new FileTarget();
                LogFileTarget.FileName                = @"${basedir}/Components/Lazysplits/logs/log.txt";
                LogFileTarget.ArchiveNumbering        = NLog.Targets.ArchiveNumberingMode.Date;
                LogFileTarget.ArchiveDateFormat       = "yyyyMMddHHmmss";
                LogFileTarget.MaxArchiveFiles         = 20;
                LogFileTarget.ArchiveOldFileOnStartup = true;
                #if DEBUG
                LogFileTarget.Layout = @"NLog|${date:format=HH\:mm\:ss.ff}|${pad:padding=5:inner=${level}}|${logger}|${message}";
                LoggingRule FileRule = new LoggingRule("*", LogLevel.Trace, LogFileTarget);
                #else
                LogFileTarget.Layout = @"NLog|${date:format=HH\:mm\:ss.ff}|${logger}|${message}";
                LoggingRule FileRule = new LoggingRule("*", LogLevel.Info, LogFileTarget);
                #endif

                LogConfig.AddTarget("File", LogFileTarget);
                LogConfig.LoggingRules.Add(FileRule);

                //console log
                #if DEBUG
                TraceTarget LogTraceTarget = new TraceTarget();
                LogTraceTarget.Layout = @"NLog|${date:format=HH\:mm\:ss.ff}|${pad:padding=5:inner=${level}}|${logger}|${message}";
                LoggingRule TraceRule = new LoggingRule("*", LogLevel.Trace, LogTraceTarget);
                LogConfig.AddTarget("File", LogTraceTarget);
                LogConfig.LoggingRules.Add(TraceRule);
                #endif

                LogManager.Configuration = LogConfig;
            }
        }
예제 #15
0
        public static void Init()
        {
            if (File.Exists(Application.persistentDataPath + "/process.log"))
            {
                File.Delete(Application.persistentDataPath + "/process.log");
            }

            if (File.Exists(Application.persistentDataPath + "/error.log"))
            {
                File.Delete(Application.persistentDataPath + "/error.log");
            }

            LoggingConfiguration config = new LoggingConfiguration();

            FileTarget processLogFile = new FileTarget("process")
            {
                FileName = Application.persistentDataPath + "/process.log"
            };
            FileTarget errorLogFile = new FileTarget("error")
            {
                FileName = Application.persistentDataPath + "/error.log"
            };

            MethodCallTarget unityDebugLog = new MethodCallTarget("logconsole", LogEventAction);

            config.AddRule(LogLevel.Debug, LogLevel.Debug, unityDebugLog);
            config.AddRule(LogLevel.Info, LogLevel.Info, unityDebugLog);
            config.AddRule(LogLevel.Error, LogLevel.Error, unityDebugLog);
            config.AddRule(LogLevel.Fatal, LogLevel.Fatal, unityDebugLog);

            if (LogDebug)
            {
                config.AddRule(LogLevel.Debug, LogLevel.Debug, processLogFile);
            }

            config.AddRule(LogLevel.Info, LogLevel.Info, processLogFile);
            config.AddRule(LogLevel.Error, LogLevel.Debug, processLogFile);
            config.AddRule(LogLevel.Fatal, LogLevel.Info, processLogFile);

            config.AddRule(LogLevel.Error, LogLevel.Error, errorLogFile);
            config.AddRule(LogLevel.Fatal, LogLevel.Fatal, errorLogFile);

            LogManager.Configuration = config;
        }
예제 #16
0
        public static void AddLogger(string className, string methodName, LogLevel minLevel)
        {
            // Step 1.
            LoggingConfiguration config = LogManager.Configuration;

            // Step 2. Create target and add it to the configuration
            MethodCallTarget methodCallTarget = new MethodCallTarget();

            config.AddTarget("methodcalltarget", methodCallTarget);

            // Step 3. Set target properties
            methodCallTarget.ClassName  = className;
            methodCallTarget.MethodName = methodName;
            methodCallTarget.Parameters.Add(new MethodCallParameter(
                                                "[${date:format=yyyy\\/MM\\/dd HH\\:mm\\:ss}] [${logger}] ${message}\r\n"));

            config.LoggingRules.Add(new LoggingRule("*", minLevel, methodCallTarget));
            LogManager.ReconfigExistingLoggers();
        }
예제 #17
0
        private void EnqueuQueueBlock_OnClose_ReleasesWriters(bool forceLockingQueue)
        {
            // Setup
            var slowTarget    = new MethodCallTarget("slowTarget", (logEvent, parms) => System.Threading.Thread.Sleep(300));
            var targetWrapper = new AsyncTargetWrapper("asynSlowTarget", slowTarget)
            {
                OverflowAction    = AsyncTargetWrapperOverflowAction.Block,
                QueueLimit        = 3,
                ForceLockingQueue = forceLockingQueue,
            };

            var logFactory    = new LogFactory();
            var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory);

            loggingConfig.AddRuleForAllLevels(targetWrapper);
            logFactory.Configuration = loggingConfig;
            var logger = logFactory.GetLogger("Test");

            // Act
            long allTasksCompleted = 0;

            AsyncHelpers.ForEachItemInParallel(System.Linq.Enumerable.Range(1, 6), (ex) => Interlocked.Exchange(ref allTasksCompleted, 1), (value, cont) => { for (int i = 0; i < 100; ++i)
                                                                                                                                                              {
                                                                                                                                                                  logger.Info("Hello {0}", value);
                                                                                                                                                              }
                                                                                                                                                              cont(null); });
            Thread.Sleep(150); // Let them get stuck
            Assert.Equal(0, Interlocked.Read(ref allTasksCompleted));

            targetWrapper.Close();  // Release those who are stuck, and discard the rest

            // Assert
            for (int i = 0; i < 100; i++)
            {
                if (Interlocked.Read(ref allTasksCompleted) == 1)
                {
                    break;
                }
                Thread.Sleep(10);
            }

            Assert.Equal(1, Interlocked.Read(ref allTasksCompleted));
        }
예제 #18
0
        /// <summary>
        /// Configure logger by MethodCallTarget
        /// </summary>
        /// <param name="target"></param>
        public void configure(MethodCallTarget target)
        {
            this.target = target;

            lock (sync)
            {
                LogManager.ConfigurationChanged -= onCfgLoggerChanged;
                LogManager.ConfigurationChanged += onCfgLoggerChanged;

                initLoggerCfg();

                LSender.SReceived -= onSReceived;
                LSender.SReceived += onSReceived;

                Components.LSender.Sent -= onLSenderSent;
                Components.LSender.Sent += onLSenderSent;
            }

            Log.Trace($"Log('{target.ClassName}') is configured for: '{GuidList.PACKAGE_LOGGER}'");
        }
예제 #19
0
        private static void AddDebugTarget(LoggingConfiguration logConfig)
        {
            LogManager.ThrowExceptions = true;

            var logDebug = new MethodCallTarget("logdebug")
            {
                ClassName  = typeof(DebugService).AssemblyQualifiedName,
                MethodName = nameof(TargetDebug),
                Parameters =
                {
                    new MethodCallParameter(STRUCLOG_TIME),
                    new MethodCallParameter(STRUCLOG_LEVEL),
                    new MethodCallParameter(STRUCLOG_LOGGER),
                    new MethodCallParameter(STRUCLOG_MESSAGE)
                }
            };

            _logConfiguration.AddTarget(logDebug);
            _logConfiguration.AddRule(LogLevel.Debug, LogLevel.Fatal, logDebug);
        }
예제 #20
0
        public MainWindow()
        {
            InitializeComponent();

            LogMessages = Messages;

            var config = new LoggingConfiguration();
            MethodCallTarget target = new MethodCallTarget();

            target.ClassName  = typeof(MainWindow).AssemblyQualifiedName;
            target.MethodName = "LogMethod";
            target.Parameters.Add(new MethodCallParameter("${level}"));
            target.Parameters.Add(new MethodCallParameter("${message}"));
            target.Parameters.Add(new MethodCallParameter("${exception:format=tostring}"));
            config.AddTarget("gui", target);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, target));
            LogManager.Configuration = config;

            ChangeGui();
        }
예제 #21
0
        private static void AddDebugTarget(LoggingConfiguration logConfig)
        {
            NLog.LogManager.ThrowExceptions = true;

            var logDebug = new MethodCallTarget("logdebug")
            {
                ClassName  = typeof(DebugService).AssemblyQualifiedName,
                MethodName = nameof(DebugService.TargetDebug),
                Parameters =
                {
                    new MethodCallParameter("${time:invariant=true}"),
                    new MethodCallParameter("${level}"),
                    new MethodCallParameter("${logger}"),
                    new MethodCallParameter("${message}")
                }
            };

            _logConfiguration.AddTarget(logDebug);
            _logConfiguration.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logDebug);
        }
예제 #22
0
        public static void Init()
        {
            LoggingConfiguration config = new LoggingConfiguration();
            string log_fmt = "${date:format=yyyy/MM/dd HH\\:mm\\:ss\\:fff} [${processid}] ${level}: "
                             + "${message}${onexception:${newline}}${exception:format=tostring}";

#if DEBUG
            var dbg_target = new DebuggerTarget("Debugger")
            {
                Layout = log_fmt
            };
            config.AddTarget(dbg_target);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, dbg_target);
#endif

            var console_target = new ConsoleTarget("Console")
            {
                Layout = log_fmt
            };
            config.AddTarget(console_target);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, console_target);

            var file_target = new FileTarget("File")
            {
                Layout                       = log_fmt,
                FileName                     = Path.Combine(Utils.LocalAppDataDir, "wincompose.log"),
                ConcurrentWrites             = true,
                ArchiveEvery                 = FileArchivePeriod.Day,
                EnableArchiveFileCompression = true,
                ArchiveNumbering             = ArchiveNumberingMode.Rolling,
                MaxArchiveFiles              = 10,
            };
            config.AddTarget(file_target);
            config.AddRule(LogLevel.Info, LogLevel.Fatal, file_target);

            var gui_target = new MethodCallTarget("MyTarget", Debug);
            config.AddTarget(gui_target);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, gui_target);

            LogManager.Configuration = config;
        }
        public static void EnsureInitialize()
        {
            var initialized = Interlocked.CompareExchange(ref _initialized, new object(), null);

            if (initialized == null)
            {
                LogManager.ConfigurationChanged +=
                    (ss, ee) =>
                {
                    // NLog configuration internally reloads when LogManager.Configuration is re/assigned (bad design!)
                    // and it seems to be the only way to propagate our changes:
                    //   - LogManager.Configuration.Reload() reloads the original file configuration
                    //   - LogManager.ReconfigExistingLoggers() does not process our new LogTarget
                    //
                    // When setting LogManager.Configuration, NLog raise the event ConfigurationChanged
                    // so we must first check that our LogTarget is not already registered

                    if (LogManager.Configuration != null && LogManager.Configuration.FindTargetByName("Multiagent-AgentLogDataSource") == null)
                    {
                        var logTarget = new MethodCallTarget();
                        logTarget.ClassName  = typeof(BrokerLogDataSource).AssemblyQualifiedName;
                        logTarget.MethodName = "LogCallback";
                        logTarget.Parameters.Add(new MethodCallParameter("${longdate}"));
                        logTarget.Parameters.Add(new MethodCallParameter("${level}"));
                        logTarget.Parameters.Add(new MethodCallParameter("${logger}"));
                        logTarget.Parameters.Add(new MethodCallParameter("${event-context:item=agent-id}"));
                        logTarget.Parameters.Add(new MethodCallParameter("${message}"));
                        logTarget.Parameters.Add(new MethodCallParameter("${exception:format=tostring}"));

                        LogManager.Configuration.AddTarget("Multiagent-AgentLogDataSource", logTarget);
                        LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, logTarget));

                        LogManager.Configuration = LogManager.Configuration;
                    }
                };

                // force a configuration reload to register our LogTarget (see comment above)
                LogManager.Configuration = LogManager.Configuration;
            }
        }
예제 #24
0
        private static void TestMethodCall(MethodCallRecord expected, string methodName, string className)
        {
            var target = new MethodCallTarget
            {
                Name = "t1",
                ClassName = className,
                MethodName = methodName
            };
            target.Parameters.Add(new MethodCallParameter("param1", "test1"));
            target.Parameters.Add(new MethodCallParameter("param2", "2", typeof(int)));

            var configuration = new LoggingConfiguration();
            configuration.AddTarget(target);
            configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target));
            LogManager.Configuration = configuration;

            LastCallTest = null;

            LogManager.GetCurrentClassLogger().Debug("test method 1");

            Assert.Equal(expected, LastCallTest);
        }
예제 #25
0
        private static void configureLogger(string allEntriesFileName, string errorEntriesFileName)
        {
            string layoutFormat         = @"${date:format=yyyyMMdd HH\:mm\:ss} ${logger}.${level} ${message}";
            var    config               = new LoggingConfiguration();
            var    allEntriesFileTarget = new FileTarget();

            allEntriesFileTarget.FileName = allEntriesFileName;
            allEntriesFileTarget.Layout   = layoutFormat;
            config.AddTarget("file", allEntriesFileTarget);

            var errorEntriesFileTarget = new FileTarget();

            errorEntriesFileTarget.FileName = errorEntriesFileName;
            errorEntriesFileTarget.Layout   = layoutFormat;
            config.AddTarget("file", errorEntriesFileTarget);

            MethodCallTarget methodTarget = new MethodCallTarget();

            methodTarget.ClassName  = typeof(LogEventBroadcaster).AssemblyQualifiedName;
            methodTarget.MethodName = "log";
            methodTarget.Parameters.Add(new MethodCallParameter("${message}"));
            config.AddTarget("broadcaster", methodTarget);

            var rule1 = new LoggingRule("*", LogLevel.Info, methodTarget);

            config.LoggingRules.Add(rule1);

            var rule2 = new LoggingRule("*", LogLevel.Trace, allEntriesFileTarget);

            config.LoggingRules.Add(rule2);

            var rule3 = new LoggingRule("*", LogLevel.Warn, errorEntriesFileTarget);

            config.LoggingRules.Add(rule3);

            LogManager.Configuration = config;
        }
예제 #26
0
        private static ILogger GetLog()
        {
            var config     = new NLog.Config.LoggingConfiguration();
            var fileTarget = new FileTarget("logfile")
            {
                FileName             = CurrentLogPath,
                ArchiveEvery         = FileArchivePeriod.Day,
                ArchiveNumbering     = ArchiveNumberingMode.DateAndSequence,
                KeepFileOpen         = true,
                ConcurrentWrites     = false,
                AutoFlush            = false,
                OpenFileFlushTimeout = 1,
                Layout = "${longdate} ${sequenceid:padding=6} ${level:uppercase=true:padding=-5} ${message} ${onexception:" +
                         "${newline}${exception:format=ToString}" +
                         ":when=not contains('${exception:format=ShortType}','TaskCanceledException')}",
            };
            var asyncFileTarget = new AsyncTargetWrapper(fileTarget)
            {
                TimeToSleepBetweenBatches = 0,
                OverflowAction            = AsyncTargetWrapperOverflowAction.Block,
                BatchSize = 500,
            };
            var consoleTarget = new ColoredConsoleTarget("logconsole")
            {
                Layout = "${longdate} ${level:uppercase=true:padding=-5} ${message} ${onexception:" +
                         "${newline}${exception:format=Message}" +
                         ":when=not contains('${exception:format=ShortType}','TaskCanceledException')}",
            };
            var watchdogTarget = new MethodCallTarget("watchdog")
            {
                ClassName  = typeof(Watchdog).AssemblyQualifiedName,
                MethodName = nameof(Watchdog.OnLogHandler),
            };

            watchdogTarget.Parameters.AddRange(new[]
            {
                new MethodCallParameter("${level}"),
                new MethodCallParameter("${message}"),
            });
#if DEBUG
            config.AddRule(LogLevel.Trace, LogLevel.Fatal, consoleTarget, "default"); // only echo messages from default logger to the console
#else
            config.AddRule(LogLevel.Info, LogLevel.Fatal, consoleTarget, "default");
#endif
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, asyncFileTarget);
            config.AddRule(LogLevel.Info, LogLevel.Fatal, watchdogTarget);

            var ignoreFilter1 = new ConditionBasedFilter {
                Condition = "contains('${message}','TaskCanceledException')", Action = FilterResult.Ignore,
            };
            var ignoreFilter2 = new ConditionBasedFilter {
                Condition = "contains('${message}','One or more pre-execution checks failed')", Action = FilterResult.Ignore,
            };
            foreach (var rule in config.LoggingRules)
            {
                rule.Filters.Add(ignoreFilter1);
                rule.Filters.Add(ignoreFilter2);
            }
            LogManager.Configuration = config;
            return(LogManager.GetLogger("default"));
        }
예제 #27
0
        /// <summary>
        /// Configures logging targets and rules.
        /// </summary>
        internal static void ConfigureLoggers()
        {
            const bool keepFileOpen = true;

            var engineFileTarget = new FileTarget
            {
                Name      = "EngineFileTarget",
                FileName  = "${basedir}/logs/engine.log",
                Layout    = "${date:format=HH\\:mm\\:ss.fff} (${threadid}) ${logger:shortName=true}: ${message}",
                Encoding  = Encoding.UTF8,
                AutoFlush = true,
                DeleteOldFileOnStartup  = true,
                CreateDirs              = true,
                KeepFileOpen            = keepFileOpen,
                ConcurrentWrites        = true,
                ConcurrentWriteAttempts = 1,
            };

            ArchiveTarget(engineFileTarget);

            var editorFileTarget = new FileTarget
            {
                Name      = "EditorFileTarget",
                FileName  = "${basedir}/logs/editor.log",
                Layout    = "${date:format=HH\\:mm\\:ss.fff} (${threadid}) ${logger:shortName=true}: ${message}",
                Encoding  = Encoding.UTF8,
                AutoFlush = true,
                DeleteOldFileOnStartup  = true,
                CreateDirs              = true,
                KeepFileOpen            = keepFileOpen,
                ConcurrentWriteAttempts = 1,
            };

            var scriptFileTarget = new FileTarget
            {
                Name      = "ScriptFileTarget",
                FileName  = "${basedir}/logs/scripts.log",
                Layout    = "${longdate} - ${logger:shortName=true}: ${message}",
                Encoding  = Encoding.UTF8,
                AutoFlush = true,
                DeleteOldFileOnStartup = true,
                CreateDirs             = true,
                KeepFileOpen           = keepFileOpen,
                ConcurrentWrites       = true,
            };

            ArchiveTarget(scriptFileTarget);

            var engineMethodTarget = new MethodCallTarget
            {
                Name       = "EngineMethodTarget",
                ClassName  = "dEngine.Services.LogService, dEngine",
                MethodName = nameof(OnLog),
            };

            engineMethodTarget.Parameters.Add(new MethodCallParameter {
                Layout = "${logger}"
            });
            engineMethodTarget.Parameters.Add(new MethodCallParameter {
                Layout = "${level}"
            });
            engineMethodTarget.Parameters.Add(new MethodCallParameter
            {
                Layout = "${date:format=HH\\:mm\\:ss.fff} - ${message}"
            });

            if (LogManager.Configuration == null)
            {
                LogManager.Configuration = new LoggingConfiguration();
            }

            var logConfig = LogManager.Configuration;

            logConfig.AddTarget(engineMethodTarget);
            logConfig.AddTarget(engineFileTarget);
            logConfig.AddTarget(editorFileTarget);
            logConfig.AddTarget(scriptFileTarget);

            logConfig.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Trace, engineMethodTarget));
            logConfig.LoggingRules.Add(new LoggingRule("dEngine.*", NLog.LogLevel.Trace, engineFileTarget));
            logConfig.LoggingRules.Add(new LoggingRule("dEditor.*", NLog.LogLevel.Trace, editorFileTarget));
            logConfig.LoggingRules.Add(new LoggingRule("I:*", NLog.LogLevel.Trace, scriptFileTarget));

            LogManager.ReconfigExistingLoggers();
        }