예제 #1
0
파일: FeLog.cs 프로젝트: pacojq/Ferret
        internal static void Initialize()
        {
            // Targets where to log to: File and Console
            //var logfile = new FileTarget("logfile") { FileName = "file.txt" };
            
            // Application logger
            ColoredConsoleTarget appConsole = new ColoredConsoleTarget("logconsole");
            appConsole.Header = Layout.FromString("${date} | Welcome to FerretEngine\n");
            appConsole.Layout = Layout.FromString("${date} | App    [${level:uppercase=true}]\t${message}");
            
            
            // Internal Logger
            ColoredConsoleTarget internalConsole = new ColoredConsoleTarget("internalConsole");
            internalConsole.Layout = Layout.FromString("${date} | Ferret [${level:uppercase=true}]\t${message}");
            
            
            
            LoggingConfiguration config = new NLog.Config.LoggingConfiguration();
#if DEBUG
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, appConsole, "Application");
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, internalConsole, "Ferret");
#else
            config.AddRule(LogLevel.Info, LogLevel.Fatal, appConsole, "Application");
            config.AddRule(LogLevel.Info, LogLevel.Fatal, internalConsole, "Ferret");
#endif
            //config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); LOG TO FILE
            
            LogManager.Configuration = config;// Apply config 
            _logger = LogManager.GetLogger("Application");
            _ferretLogger = LogManager.GetLogger("Ferret");
        }
예제 #2
0
        /// <summary>
        /// Skapar och returnerar en logger,
        /// om det redan har skapats en logger tidigare så returneras den existerande.
        /// </summary>
        /// <returns>PersonsokLogger</returns>
        public static PersonsokLogger CreatePersonsokLogger()
        {
            LoggingConfiguration logConfig = new NLog.Config.LoggingConfiguration();
            FileTarget           logfile   = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "personsok.log"
            };
            ConsoleTarget logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            logConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logconsole);
            logConfig.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = logConfig;

            IConfigurationRoot rootConfig = new ConfigurationBuilder()
                                            .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                                            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                            .Build();

            IServiceProvider serviceProvider = new ServiceCollection()
                                               .AddTransient <PersonsokLogger>()
                                               .AddLogging(loggingBuilder =>
            {
                loggingBuilder.ClearProviders();
                loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                loggingBuilder.AddNLog(rootConfig);
            })
                                               .BuildServiceProvider();

            return(serviceProvider.GetRequiredService <PersonsokLogger>());
        }
예제 #3
0
        private void Main_Load(object sender, EventArgs e)
        {
            //NLog Preparations
            filetg.FileName         = "${basedir}/logs/pepperlogfile.txt";
            filetg.ArchiveFileName  = "${basedir}/logs/peplog.{#}.txt";
            filetg.ArchiveEvery     = FileArchivePeriod.Day;
            filetg.ArchiveNumbering = ArchiveNumberingMode.Date;
            filetg.MaxArchiveFiles  = 7;
            filetg.ConcurrentWrites = true;

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Trace, LogLevel.Fatal, filetg);

            NLog.LogManager.Configuration = config;
            // Example usage & Logging Level
            //logger.Trace("trace log message");
            //logger.Debug("debug log message");
            //logger.Info("info log message");
            //logger.Warn("warn log message");
            //logger.Error("error log message");
            //logger.Fatal("fatal log message");
            //End Preparation

            logger.Trace("Pepper Start");


            Th.checkGDfiles();
            Thread.Sleep(5000);

            Th.CheckMail();
            Thread.Sleep(5000);
            Timer.Enabled = true;
        }
예제 #4
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);
        }
예제 #5
0
        public Logger(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            _logger = LogManager.GetCurrentClassLogger();
            var config = new NLog.Config.LoggingConfiguration();

            // Targets where to log to: File and Console
            var debuglogfile = new NLog.Targets.FileTarget("debuglog")
            {
                FileName = "DebugLog.txt"
            };
            var fatallogfile = new NLog.Targets.FileTarget("fatallog")
            {
                FileName = "FatalLog.txt"
            };

            // Rules for mapping loggers to targets
            config.AddRule(LogLevel.Info, LogLevel.Fatal, fatallogfile);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, debuglogfile);

            // Apply config
            NLog.LogManager.Configuration = config;
        }
예제 #6
0
파일: Form1.cs 프로젝트: fishca/MetaRead
        public Form1()
        {
            InitializeComponent();
            MetaTypeSet.EventError += MetaTypeSet_EventError; // подписываемся на событие EventError. Если оно произойдет, то запустить метод (Analyze_EventError).
            Tree.EventError        += Tree_EventError;

            #region Logs
            var config = new NLog.Config.LoggingConfiguration();

            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "log_file.txt"
            };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");


            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

            NLog.LogManager.Configuration = config;

            log = LogManager.GetCurrentClassLogger();

            #endregion
        }
예제 #7
0
    /**
     * Configures the Console/File logging.
     *
     * TODO: make it configurable (log levels, file name).
     */
    public static void ConfigureLogging()
    {
        var config  = new NLog.Config.LoggingConfiguration();
        var logfile = new NLog.Targets.FileTarget("logfile")
        {
            FileName = "app.log"
        };
        var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

        config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
        config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
        NLog.LogManager.Configuration = config;
    }
예제 #8
0
파일: Class1.cs 프로젝트: Ajololr/MPP
        public DependenciesConfiguration()
        {
            LoggingConfiguration config  = new NLog.Config.LoggingConfiguration();
            FileTarget           logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "debugOutput.txt"
            };
            ConsoleTarget logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;
        }
예제 #9
0
        public void SetUp()
        {
            System.Net.ServicePointManager.DefaultConnectionLimit = 1000;
            Console.WriteLine("Initializing tests (setting console loggers)...");
            SetUpDebugListeners();

            var originalFormatter = NLog.Config.ConfigurationItemFactory.Default.ValueFormatter;

            ConfigurationItemFactory.Default.ValueFormatter = new NLogValueFormatter(originalFormatter, false);
            ConsoleTarget consoleTarget = new ConsoleTarget("testconsole");
            var           config        = new NLog.Config.LoggingConfiguration();

            config.AddRule(LogLevel.Trace, LogLevel.Fatal, consoleTarget);
            consoleTarget.Layout          = "[${processid:padCharacter=0:padding=5},${threadid:padCharacter=0:padding=2},${date:universalTime=true:format=HH\\:mm\\:ss\\.fff},${level:padding=-5:uppercase=true}] ${message}${onexception:${newline}${literal:text=EXCEPTION OCCURRED}${newline}${exception:format=message}}";
            NLog.LogManager.Configuration = config;
            EventStore.Common.Log.LogManager.SetLogFactory(x => new NLogger(x));

            Application.AddDefines(new[] { Application.AdditionalCommitChecks });
            LogEnvironmentInfo();

            if (!Debugger.IsAttached)
            {
                PortsHelper.InitPorts(IPAddress.Loopback);
            }
        }
예제 #10
0
        protected static void TestLogger(Action <ILogger, Func <List <string> > > act)
        {
            // These layout renderers need to registered statically as ultimately ConfigurationItemFactory.Default is called in the call stack.
            LayoutRenderer.Register <ApmTraceIdLayoutRenderer>(ApmTraceIdLayoutRenderer.Name);             //generic
            LayoutRenderer.Register <ApmTransactionIdLayoutRenderer>(ApmTransactionIdLayoutRenderer.Name); //generic

            var logFactory = new LogFactory();
            var logConfig  = new Config.LoggingConfiguration(logFactory);
            var ecsLayout  = new EcsLayout();

            ecsLayout.ExcludeProperties.Add("NotX");
            var memoryTarget = new MemoryTarget {
                Layout = ecsLayout, OptimizeBufferReuse = true
            };

            logConfig.AddRule(LogLevel.Trace, LogLevel.Fatal, memoryTarget);
            logConfig.DefaultCultureInfo = System.Globalization.CultureInfo.InvariantCulture;
            logFactory.Configuration     = logConfig;

            List <string> GetLogEvents() => memoryTarget.Logs.ToList();

            var logger = logFactory.GetCurrentClassLogger();

            act(logger, GetLogEvents);
        }
예제 #11
0
        /*  función estática InitLogger() => void
         *      Inicializa el servicio de logging de la aplicación
         */
        public static void InitLogger()
        {
            LoggingConfiguration config = new NLog.Config.LoggingConfiguration();

            // Establece las salidas de logging a consola y archivo
            Target logconsole = new NLog.Targets.ConsoleTarget("logconsole");
            Target logfile    = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "nlog.log"
            };

            // Añade las reglas de configuración con los umbrales de los niveles de seguridad
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logfile);

            // Aplica la configuración
            NLog.LogManager.Configuration = config;
        }
예제 #12
0
    private void SetUpNLog()
    {
        var config = new NLog.Config.LoggingConfiguration();

        // Targets where to log to: File and Console
        var logfile = new NLog.Targets.FileTarget("logfile")
        {
            FileName = "backupclientlogfile_helperservice.txt"
        };
        var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

        // Rules for mapping loggers to targets
        config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logconsole);
        config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logfile);

        // Apply config
        LogManager.Configuration = config;

        _logger = LogManager.GetCurrentClassLogger();
    }
예제 #13
0
        private Logger()
        {
            LayoutRenderer.Register <LayoutRenderers.ElapsedTimeLayoutRenderer>("elapsed-time");
            LayoutRenderer.Register <LayoutRenderers.RealTimeLayoutRenderer>("real-time");
            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "pluginlog.log", ArchiveEvery = NLog.Targets.FileArchivePeriod.Day, MaxArchiveFiles = 10, ArchiveFileName = "logs/log.{###}.log", ArchiveNumbering = NLog.Targets.ArchiveNumberingMode.Rolling
            };

            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;
            log = LogManager.GetCurrentClassLogger();
            LogMessage(TracingLevel.DEBUG, "Logger Initialized");
        }
예제 #14
0
        private static void ConfigureLogging()
        {
            // If there is a configuration file then this will already be set
            if (LogManager.Configuration != null)
            {
                return;
            }

            var config     = new NLog.Config.LoggingConfiguration();
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            logconsole.Layout = "${longdate}|${level:uppercase=true}|${message}";
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);

            LogManager.Configuration = config;
        }
예제 #15
0
 public void AddRule_min_max()
 {
     var config = new LoggingConfiguration();
     config.AddTarget(new FileTarget {Name = "File"});
     config.AddRule(LogLevel.Info, LogLevel.Error, "File", "*a");
     Assert.NotNull(config.LoggingRules);
     Assert.Equal(1, config.LoggingRules.Count);
     var rule1 = config.LoggingRules.FirstOrDefault();
     Assert.NotNull(rule1);
     Assert.Equal(false, rule1.Final);
     Assert.Equal("*a", rule1.LoggerNamePattern);
     Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Fatal));
     Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Error));
     Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Warn));
     Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Info));
     Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Debug));
     Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Trace));
     Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Off));
 }
예제 #16
0
        public static ILoggerManager GetLoggingService(ILoggingConfiguration loggingConfiguration)
        {
            var config = new NLog.Config.LoggingConfiguration();

            LogLevel minLogLevel = LogLevel.Error;

            switch (loggingConfiguration.LogLevel)
            {
            case Types.Enums.LogLevel.Info:
                minLogLevel = LogLevel.Info;
                break;

            case Types.Enums.LogLevel.Trace:
                minLogLevel = LogLevel.Trace;
                break;

            case Types.Enums.LogLevel.Debug:
                minLogLevel = LogLevel.Debug;
                break;

            case Types.Enums.LogLevel.Warn:
                minLogLevel = LogLevel.Warn;
                break;

            case Types.Enums.LogLevel.Error:
                minLogLevel = LogLevel.Error;
                break;

            case Types.Enums.LogLevel.Fatal:
                minLogLevel = LogLevel.Fatal;
                break;
            }

            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = "log.txt",
                DeleteOldFileOnStartup = true,
            };

            if (loggingConfiguration.LogVerbosity == LogVerbosity.Quit)
            {
                logfile.Layout =
                    "Local-Date=${longdate}|Level=${level}|Log-Message=${message}|Error-Message=${event-context:item=error-message}";
            }
            else if (loggingConfiguration.LogVerbosity == LogVerbosity.Diagnostic)
            {
                logfile.Layout =
                    "Local-Date=${longdate}|Level=${level}|Log-Message=${message}|Error-Source=${event-context:item=error-source}|Error-Class=${event-context:item=error-class}|Error-Method=${event-context:item=error-method}|Error-Message=${event-context:item=error-message}|Inner-Error-Message=${event-context:item=inner-error-message}";
            }
            else
            {
                logfile.Layout =
                    "Local-Date=${longdate}|Level=${level}|Log-Message=${message}|Error-Source=${event-context:item=error-source}|Error-Class=${event-context:item=error-class}|Error-Method=${event-context:item=error-method}|Error-Message=${event-context:item=error-message}|Inner-Error-Message=${event-context:item=inner-error-message}|Stack-Trace=${event-context:item=stack-trace}";
            }

            config.AddRule(minLogLevel, LogLevel.Fatal, logfile);

            // Apply config
            NLog.LogManager.Configuration = config;

            ConfigurationItemFactory.Default.LayoutRenderers
            .RegisterDefinition("utc_date", typeof(UtcDateRenderer));

            if (!loggingConfiguration.IsLoggingEnabled)
            {
                LogManager.GlobalThreshold = LogLevel.Off;
            }

            ILoggerManager logger = (ILoggerManager)NLog.LogManager.GetLogger("NLogLogger", typeof(LoggerManager));

            return(logger);
        }
예제 #17
0
파일: Logging.cs 프로젝트: scowalt/RTCV
        public static void StartLogging(string filename)
        {
            ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("InvariantCulture", typeof(InvariantCultureLayoutRendererWrapper));
            var config = new NLog.Config.LoggingConfiguration();


            for (int i = logsToKeep; i >= 0; i--)
            {
                var _filename = getFormattedLogFilename(filename, i - 1);
                if (File.Exists(_filename))
                {
                    var newName = getFormattedLogFilename(filename, i);

                    if (string.IsNullOrEmpty(newName)) //If something went wrong generating the name, just give up
                    {
                        break;
                    }

                    try
                    {
                        File.Copy(_filename, newName, true);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Failed to rotate log file {_filename} to {newName}\n{e}");
                    }
                }
            }

            try
            {
                File.Delete(filename);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Failed to delete old log!\n{e}");
            }

            if (minLevel == LogLevel.Trace)
            {
                CurrentLayout = traceLayout;
            }

            // var logfile = new NLog.Targets.FileTarget("logfile") { FileName = filename, Layout = layout };
            var logconsole = new NLog.Targets.ColoredConsoleTarget("logconsole")
            {
                Layout = CurrentLayout
            };

            bool isDebug = false;

            Debug.Assert(isDebug = true);
            if (Environment.GetCommandLineArgs().Contains("-TRACE") || isDebug)
            {
                config.AddRule(LogLevel.Trace, LogLevel.Fatal, logconsole);
            }
            else
            {
                config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole);
            }
            // Rules for mapping loggers to targets
            //config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile);

            // Apply config
            NLog.LogManager.Configuration = config;
            Common.ConsoleHelper.CreateConsole(filename);
            if (!Environment.GetCommandLineArgs().Any(x => string.Equals(x, "-CONSOLE", StringComparison.OrdinalIgnoreCase)))
            {
                Common.ConsoleHelper.HideConsole();
            }

            GlobalLogger = LogManager.GetLogger("Global");
        }