/// <summary>
        /// Initializes a new instance of the <see cref="SumoLogicTargetTest"/> class.
        /// </summary>
        public SumoLogicTargetTest()
        {
            this.messagesHandler = new MockHttpMessageHandler();
            this.sumoLogicTarget = new SumoLogicTarget(null, this.messagesHandler);
            this.sumoLogicTarget.Url = "http://www.fakeadress.com";
            this.sumoLogicTarget.Layout = @"${level:upperCase=true}: ${message}";
            this.sumoLogicTarget.SourceName = "SumoLogicTargetTest";
            this.sumoLogicTarget.Name = "SumoLogicTargetTest";
            if (LogManager.Configuration == null)
            {
                LogManager.Configuration = new LoggingConfiguration();
            }

            LogManager.Configuration.AddTarget(this.sumoLogicTarget.SourceName, this.sumoLogicTarget);
            LoggingRule rule = new LoggingRule("SumoLogicTargetTest", LogLevel.Debug, this.sumoLogicTarget);
            LogManager.Configuration.LoggingRules.Add(rule);
            LogManager.Configuration.Reload();
            LogManager.ReconfigExistingLoggers();
            this.logger = LogManager.GetLogger("SumoLogicTargetTest");
        }
예제 #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SumoLogicTargetTest"/> class.
        /// </summary>
        public SumoLogicTargetTest()
        {
            messagesHandler                = new MockHttpMessageHandler();
            sumoLogicTarget                = new SumoLogicTarget(null, messagesHandler);
            sumoLogicTarget.Url            = "http://www.fakeadress.com";
            sumoLogicTarget.Layout         = @"${level:upperCase=true}: ${message}${exception:format=tostring}${newline}";
            sumoLogicTarget.SourceName     = "SumoLogicTargetTest";
            sumoLogicTarget.SourceCategory = "SumoLogicTargetSourceCategory";
            sumoLogicTarget.SourceHost     = "${machinename}";
            sumoLogicTarget.Name           = "SumoLogicTargetTest";
            if (LogManager.Configuration == null)
            {
                LogManager.Configuration = new LoggingConfiguration();
            }

            LogManager.Configuration.AddTarget(sumoLogicTarget.SourceName, sumoLogicTarget);
            LoggingRule rule = new LoggingRule("SumoLogicTargetTest", LogLevel.Debug, sumoLogicTarget);

            LogManager.Configuration.LoggingRules.Add(rule);
            LogManager.Configuration.Reload();
            LogManager.ReconfigExistingLoggers();
            logger = LogManager.GetLogger("SumoLogicTargetTest");
        }
예제 #3
0
파일: Program.cs 프로젝트: theCanary/RBCmd
        private static void SetupNLog()
        {
            if (File.Exists(Path.Combine(BaseDirectory, "Nlog.config")))
            {
                return;
            }
            var config   = new LoggingConfiguration();
            var loglevel = LogLevel.Info;

            var layout = @"${message}";

            var consoleTarget = new ColoredConsoleTarget();

            config.AddTarget("console", consoleTarget);

            consoleTarget.Layout = layout;

            var rule1 = new LoggingRule("*", loglevel, consoleTarget);

            config.LoggingRules.Add(rule1);

            LogManager.Configuration = config;
        }
예제 #4
0
        // Настройка логгера
        public static void LoggerConfig()
        {
            LoggingConfiguration config = new LoggingConfiguration();

            FileTarget fileTarget = new FileTarget();

            config.AddTarget("file", fileTarget);

            fileTarget.DeleteOldFileOnStartup = true;                                                                        // Удалатья страый файл при запуске
            fileTarget.KeepFileOpen           = false;                                                                       //Держать файл открытым
            fileTarget.ConcurrentWrites       = true;                                                                        //
            fileTarget.Encoding        = Encoding.Unicode;                                                                   // Кодировка файла логгера
            fileTarget.ArchiveEvery    = FileArchivePeriod.Day;                                                              // Период архивирования старых логов
            fileTarget.Layout          = NLog.Layouts.Layout.FromString("${longdate} | ${uppercase:${level}} | ${message}"); // Структура сообщения
            fileTarget.FileName        = NLog.Layouts.Layout.FromString("${basedir}/logs/${shortdate}.log");                 //Структура названия файлов
            fileTarget.ArchiveFileName = NLog.Layouts.Layout.FromString("${basedir}/logs/archives/{shortdate}.rar");         // Структура названия архивов

            LoggingRule ruleFile = new LoggingRule("*", LogLevel.Trace, fileTarget);                                         // Минимальный уровень логгирования - Trace

            config.LoggingRules.Add(ruleFile);

            LogManager.Configuration = config;
        }
예제 #5
0
        private static void ConfigureConsoleLogger()
        {
            var config = new LoggingConfiguration();

            if (HasFlags("CERTES_DEBUG"))
            {
                config.LoggingRules.Add(
                    new LoggingRule("*", LogLevel.Debug, new ColoredConsoleTarget
                    {
                        Layout = "${message}${onexception:${newline}${exception:format=tostring}}",
                    }));
            }
            else
            {
                var consoleRule = new LoggingRule("*", LogLevel.Info, new ColoredConsoleTarget
                {
                    Layout = "${message}",
                });
                config.LoggingRules.Add(consoleRule);
            }

            LogManager.Configuration = config;
        }
예제 #6
0
        public virtual Logger InitLog(string logfileName, string logLayoutFormat)
        {
            if (string.IsNullOrEmpty(logLayoutFormat))
            {
                return(this.InitLog(logfileName));
            }
            LoggingConfiguration configuration = new LoggingConfiguration();
            FileTarget           target        = new FileTarget();

            configuration.RemoveTarget("file");
            configuration.AddTarget("file", target);
            target.FileName = string.Format("{0}.txt", Path.Combine(Path.GetDirectoryName(logfileName), Path.GetFileNameWithoutExtension(logfileName)));
            target.Layout   = logLayoutFormat;
            LoggingRule item = new LoggingRule("*", NLog.LogLevel.Trace, target);

            configuration.LoggingRules.Clear();
            configuration.LoggingRules.Add(item);
            LogManager.Configuration = configuration;
            Logger logger = this._NLoger = LogManager.GetLogger(logfileName);

            this.AddNewLineLayOut();
            return(this._NLoger = logger);
        }
예제 #7
0
        public Logger GetFileTargetLogger(string name)
        {
            lock (lockObject)
            {
                if (LogManager.Configuration == null)
                {
                    HandleNullConfiguration();
                }

                name = name.ToLowerInvariant();
                Logger existing = GetLoggers().FirstOrDefault(e => e.Name == name);

                if (existing != null)
                {
                    return(existing);
                }

                string fileName = Path.Combine(new[] { LogDir, name + ".log" });

                FileInfo info = new FileInfo(fileName);

                if (!info.Directory.Exists)
                {
                    Directory.CreateDirectory(info.Directory.FullName);
                }

                FileTarget target = TargetFactory.GetDefaultFileTarget(name, fileName);

                LoggingRule rule = new LoggingRule(name, LogLevel, target);
                LogManager.Configuration.LoggingRules.Add(rule);
                LogManager.Configuration.AddTarget(target);

                LogManager.ReconfigExistingLoggers();

                return(GetLoggers().FirstOrDefault(e => e.Name == name));
            }
        }
예제 #8
0
        //the Code has to be part of the main Class / mainmethod

        /*
         * using NLog;
         * MainWindow() {
         *  LoggingConfig.Initialize();
         * }
         * private static Logger log = LogManager.GetCurrentClassLogger();
         * log.Debug("This Text will be logged");  //LogExample
         */

        public static void Initialize()
        {
            LoggingConfiguration logConfig = new LoggingConfiguration();

            FileTarget fileTarget = new FileTarget();

            logConfig.AddTarget("file", fileTarget);
            fileTarget.FileName = "AutoSF.log";
            fileTarget.ArchiveOldFileOnStartup = true;
            fileTarget.ArchiveFileName         = "AutoSF.{#}.log";
            fileTarget.ArchiveNumbering        = ArchiveNumberingMode.Rolling;
            fileTarget.MaxArchiveFiles         = 7;
            fileTarget.ConcurrentWrites        = true;
            fileTarget.KeepFileOpen            = false;
            fileTarget.Layout = @"${date:format=HH\:mm\:ss.fff} [${level}] ${logger} - ${message}";
            LoggingRule rule = new LoggingRule("*", LogLevel.Debug, fileTarget);

            logConfig.LoggingRules.Add(rule);

            //Adds output to Console
            ConsoleTarget consoleTarget = new ConsoleTarget();

            logConfig.AddTarget("console", consoleTarget);
            consoleTarget.Layout = @"${date:format=HH\:mm\:ss.fff} [${level}] ${logger} - ${message}";
            rule = new LoggingRule("*", LogLevel.Debug, consoleTarget);
            logConfig.LoggingRules.Add(rule);


            LogManager.Configuration = logConfig;

            //LogManager.DisableLogging();

            if (Environment.GetCommandLineArgs().Contains("debug"))  //only logs when debug is added as parameter.
            {
                LogManager.EnableLogging();
            }
        }
예제 #9
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;
        }
예제 #10
0
        public void ApplicationLog()
        {
            var config   = new LoggingConfiguration();
            var loglevel = LogLevel.Debug;

            var layout = @"${message}";

            var consoleTarget = new ColoredConsoleTarget();

            config.AddTarget("console", consoleTarget);

            consoleTarget.Layout = layout;

            var rule1 = new LoggingRule("*", loglevel, consoleTarget);

            config.LoggingRules.Add(rule1);

            LogManager.Configuration = config;
            var l = LogManager.GetLogger("foo");

            var sysLog = @"D:\SynologyDrive\EventLogs\HP_Spec\Application.evtx";

            var total = 0;

            using (var fs = new FileStream(sysLog, FileMode.Open, FileAccess.Read))
            {
                var es = new EventLog(fs);

                foreach (var eventRecord in es.GetEventRecords())
                //      l.Info($"Record: {eventRecord}");
                {
                    eventRecord.ConvertPayloadToXml();
                }
            }

            l.Info($"Total: {total}");
        }
예제 #11
0
        private static void Add(Assembly assembly)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }

            try
            {
                var metadata   = assembly.GetMetadata();
                var @namespace = assembly.GetName().Name;

                if (string.IsNullOrEmpty(metadata?.SentryKey) || string.IsNullOrEmpty(metadata?.SentryProject))
                {
                    Log.Info($"Skipped ({@namespace}) missing SentryKey or SentryProject");
                    return;
                }

                var target = new SentryTarget(assembly, metadata);
                var rule   = new LoggingRule($"{@namespace}*", LogLevel.Trace, target)
                {
                    Final = true
                };

                Targets[assembly] = target;

                Config.AddTarget(@namespace, target);
                Config.LoggingRules.Add(rule);

                Log.Info($"SentryTarget({@namespace})");
                LogManager.ReconfigExistingLoggers();
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
예제 #12
0
        static Log()
        {
            var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            var consoleTarget = new ColoredConsoleTarget();

            config.AddTarget("console", consoleTarget);

            var fileTarget = new FileTarget();

            config.AddTarget("file", fileTarget);

            // Step 3. Set target properties
            consoleTarget.Layout = @"${date:format=HH\\:mm\\:ss} ${logger} ${message}";
#if DEBUG
            //string fileName = "${basedir}/PersistentWindows.Log";
            string fileName = "PersistentWindows.Log";
#else
            string tempFolderPath = Path.GetTempPath();
            string fileName       = $"{tempFolderPath}/PersistentWindows.Log";
#endif
            File.Delete(fileName);
            fileTarget.FileName = fileName;

            fileTarget.Layout = "${date:format=HH\\:mm\\:ss} ${logger} ${message}";

            // Step 4. Define rules
            var rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget);
            config.LoggingRules.Add(rule1);

            var rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
            config.LoggingRules.Add(rule2);

            // Step 5. Activate the configuration
            LogManager.Configuration = config;
        }
예제 #13
0
        /// <summary>
        /// The method triggered when the command line arguments are parsed
        /// with success.
        /// </summary>
        /// <param name="options">
        /// An instance of <see cref="Options" /> containing the parsed command
        /// line arguments.
        /// </param>
        private static void CommandLineArgumentsParsed(Options options)
        {
            // Create our StructureMap registry and...
            Registry  registry  = new Registry();
            Container container = new Container(registry);

            string   logLevelStr = options.Verbosity.ToString();
            LogLevel logLevel    = LogLevel.FromString(logLevelStr);

            // Get the default NLog configuration - i.e. the one declared
            // in Nlog.config.
            LoggingConfiguration loggingConfiguration =
                LogManager.Configuration;

            // Add a rule for each target, based on the input Verbosity level.
            LoggingRule loggingRule = null;

            foreach (Target target in loggingConfiguration.AllTargets)
            {
                loggingRule = new LoggingRule("*", logLevel, target);

                loggingConfiguration.LoggingRules.Add(loggingRule);
            }

            // Get an instance.
            IOutputFileGenerator outputFileGenerator =
                container.GetInstance <IOutputFileGenerator>();

            executionSuccess = outputFileGenerator.CreateOutputFile(
                new Tuple <string, string>(
                    options.AccessKeyId,
                    options.SecretAccessKey),
                options.AwsRegion,
                options.PasswordEncryptionKeyFile,
                options.RoleArn,
                options.OutputFile);
        }
예제 #14
0
        private static Logger ConfigureLogger(LogLevel level)
        {
            var config = new LoggingConfiguration();

            var elasticTarget = new DataDogTarget
            {
                // IMPORTANT! replace "YOUR API KEY" with your DataDog API key
                ApiKey  = "YOUR API KEY",
                Service = Assembly.GetExecutingAssembly()?.GetName().Name,
                Source  = Environment.MachineName
            };
            var rule = new LoggingRule("*", elasticTarget);

            rule.EnableLoggingForLevel(level);
            config.AddTarget(elasticTarget);
            config.LoggingRules.Add(rule);

            var consoleTarget = new ConsoleTarget("console");
            var consoleRule   = new LoggingRule("*", consoleTarget);

            consoleRule.EnableLoggingForLevel(level);
            config.AddTarget(consoleTarget);
            config.LoggingRules.Add(consoleRule);

            var debugTarget = new DebugTarget("debug");
            var debugRule   = new LoggingRule("*", debugTarget);

            debugRule.EnableLoggingForLevel(level);
            config.AddTarget(debugTarget);
            config.LoggingRules.Add(debugRule);

            LogManager.Configuration = config;

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

            return(logger);
        }
예제 #15
0
        public static void SetupLogging(LogLevel logLevel)
        {
            // Step 1. Create configuration object
            var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            var debuggerTarget = new DebuggerTarget();

            config.AddTarget("debugger", debuggerTarget);

            var fileTarget = new FileTarget();

            config.AddTarget("file", fileTarget);

            // Step 3. Set target properties
            debuggerTarget.Layout      = @"${logger:shortName=True} - ${uppercase:${level}}: ${message}";
            fileTarget.FileName        = "${specialfolder:folder=MyDocuments}/Artemis/logs/${shortdate}.txt";
            fileTarget.Layout          = "${longdate}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}";
            fileTarget.ArchiveEvery    = FileArchivePeriod.Day;
            fileTarget.MaxArchiveFiles = 7;

            // Step 4. Define rules
            var rule1 = new LoggingRule("*", logLevel, debuggerTarget);

            config.LoggingRules.Add(rule1);
            var rule2 = new LoggingRule("*", logLevel, fileTarget);

            config.LoggingRules.Add(rule2);

            // Step 5. Activate the configuration
            LogManager.Configuration = config;

            // Log as fatal so it always shows
            var logger = LogManager.GetCurrentClassLogger();

            logger.Fatal("INFO: Set log level to {0}", logLevel);
        }
예제 #16
0
        public NLogLogProvider()
        {
            if (NLog.LogManager.Configuration != null)
            {
                return;
            }

            var config = new LoggingConfiguration();

#if DEBUG
            var consoleTarget = new ColoredConsoleTarget()
            {
                Layout = @"${level:uppercase=true}|${logger}:${message}${exception}"
            };

            config.AddTarget("console", consoleTarget);
            var rule1 = new LoggingRule("*", NLog.LogLevel.Debug, consoleTarget);
            config.LoggingRules.Add(rule1);
#endif

            var loggerDir  = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location);
            var fileTarget = new FileTarget()
            {
                FileName         = Path.Combine(loggerDir, "nlog.log"),
                Layout           = "${longdate}|${level:uppercase=true}:${message}${exception:format=toString}",
                KeepFileOpen     = false,
                ArchiveFileName  = Path.Combine(loggerDir, "nlog.{#####}.log"),
                ArchiveAboveSize = 4096000,
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
                MaxArchiveFiles  = 2
            };

            config.AddTarget("file", fileTarget);
            var rule2 = new LoggingRule("*", NLog.LogLevel.Debug, fileTarget);
            config.LoggingRules.Add(rule2);
            NLog.LogManager.Configuration = config;
        }
예제 #17
0
        public LogService()
        {
            var physicalPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
            var logPath      = string.Concat(physicalPath, "Durra logs");

            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }

            TargetName = "Durra";
            var template = new StringBuilder("-------------- ${level} (${longdate}) --------------${newline}");

            template.Append("${newline}");
            template.Append("Call Site: ${callsite}${newline}");
            template.Append("Exception Type: ${exception:format=Type}${newline}");
            template.Append("Exception Message:${exception:format=Message}${newline}");
            template.Append("Stack Trace: ${exception:format=StackTrace}${newline}");
            template.Append("Additional Info: ${message}${newline}");

            var target = new FileTarget();

            target.Name     = TargetName;
            target.FileName = $"{logPath}\\{Guid.NewGuid()}.log";
            target.Layout   = template.ToString();

            var config = new LoggingConfiguration();

            config.AddTarget(TargetName, target);

            var rule = new LoggingRule("*", LogLevel.Trace, target);

            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;
            _siteLogger = LogManager.GetLogger(TargetName);
        }
        public NLogFactory(string logsFolderPath = "logs")
        {
            string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            if (string.IsNullOrWhiteSpace(logsFolderPath))
            {
                logsFolderPath = assemblyFolder;
            }

            if (File.Exists("NLog.config"))
            {
                NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(assemblyFolder + "\\NLog.config", true);
            }
            else
            {
                var config = new LoggingConfiguration();

                var fileTarget = new FileTarget();
                config.AddTarget("default", fileTarget);

                if (string.IsNullOrWhiteSpace(logsFolderPath))
                {
                    logsFolderPath = "logs";
                }

                fileTarget.FileName = "${basedir}/" + logsFolderPath + "/log_${shortdate}.log";
                fileTarget.Layout   = @"${longdate} ${level} -- ${message}";
                fileTarget.Encoding = Encoding.UTF8;

                var rule2 = new LoggingRule("default", NLog.LogLevel.Trace, fileTarget);
                config.LoggingRules.Add(rule2);

                LogManager.Configuration = config;
            }

            Default = GetLogger("default");
        }
예제 #19
0
        private static void Initialize()
        {
            if (_isInitialized == false)
            {
                // Step 1. Create configuration object
                _config = new LoggingConfiguration();

                FileTarget fileTarget = new FileTarget();
                _config.AddTarget("file", fileTarget);

                string path = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

                // set the file
                fileTarget.FileName = path + string.Format("\\{0}-Log.txt", Guid.NewGuid());
                fileTarget.Layout   = "${date:format=HH\\:MM\\:ss}: ${message}";

                // don’t clutter the hard drive
                fileTarget.DeleteOldFileOnStartup = true;

                // Step 4. Define rules
                LoggingRule rule1 = new LoggingRule("*", LogLevel.Fatal, fileTarget);
                _config.LoggingRules.Add(rule1);

                LoggingRule rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
                _config.LoggingRules.Add(rule2);

                LoggingRule rule3 = new LoggingRule("*", LogLevel.Error, fileTarget);
                _config.LoggingRules.Add(rule3);

                // Step 5. Activate the configuration
                LogManager.Configuration = _config;

                _logger = LogManager.GetLogger("ScutexServiceLogger");

                _isInitialized = true;
            }
        }
예제 #20
0
파일: TestMain.cs 프로젝트: muyen2/MFT-1
        public void Usn()
        {
            var config   = new LoggingConfiguration();
            var loglevel = LogLevel.Trace;

            var layout = @"${message}";

            var consoleTarget = new ColoredConsoleTarget();

            config.AddTarget("console", consoleTarget);

            consoleTarget.Layout = layout;

            var rule1 = new LoggingRule("*", loglevel, consoleTarget);

            config.LoggingRules.Add(rule1);

            //   LogManager.Configuration = config;

            var usn4 = UsnFile.Load(@"D:\SynologyDrive\ntfs\Troy\J-stream-testing\noname.bin");

            // var usn4 = UsnFile.Load(@"D:\!downloads\J-stream-testing\$J");
            usn4.UsnEntries.Count.Should().Be(328539);
        }
예제 #21
0
        public void SetUp()
        {
            clientMock   = new Mock <IElmahioAPI>();
            messagesMock = new Mock <IMessages>();
            clientMock.Setup(x => x.Messages).Returns(messagesMock.Object);
            var target = new ElmahIoTarget(clientMock.Object)
            {
                ApiKey = "ApiKey",
                LogId  = Guid.NewGuid().ToString(),
                Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}",
            };

            var config = new LoggingConfiguration();

            config.AddTarget("elmah.io", target);

            var rule = new LoggingRule("*", LogLevel.Info, target);

            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;

            logger = LogManager.GetLogger("Test");
        }
예제 #22
0
        private void SetupVerboseLogging(string logOutputDirFullPath)
        {
            logOutputDirFullPath = Path.Combine(logOutputDirFullPath, "Verbose");

            var currentLogDir = Path.Combine(logOutputDirFullPath);

            if (!Directory.Exists(currentLogDir))
            {
                Directory.CreateDirectory(currentLogDir);
            }

            var archiveLogDir = Path.Combine(currentLogDir, "Archive");

            if (!Directory.Exists(archiveLogDir))
            {
                Directory.CreateDirectory(archiveLogDir);
            }

            MoveOldLogToArchive(currentLogDir, archiveLogDir);
            TrimOlgLogFiles(archiveLogDir, maxMegabytes: 50);

            var currentFileName = Time.Get.LocalNow.ToString("yyy-MM-dd_HH-mm-ss-ffffff") + ".txt";

            currentVerboseLogFileFullPath = Path.Combine(currentLogDir, currentFileName);
            var fileTarget = new FileTarget
            {
                ArchiveNumbering = ArchiveNumberingMode.DateAndSequence,
                KeepFileOpen     = true,
                FileName         = GetCurrentVerboseLogFileFullPath(),
                Layout           = "${date:universalTime=true}|${level}|${logger}|${message}${onexception:inner=|${exception:format=ToString}}"
            };

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

            config.LoggingRules.Add(globalrule);
        }
        public void SimpleJsonLayoutTest()
        {
            var elasticTarget = new ElasticSearchTarget();

            elasticTarget.EnableJsonLayout = true;
            elasticTarget.Layout           = new JsonLayout()
            {
                MaxRecursionLimit    = 10,
                IncludeAllProperties = true,
                Attributes           =
                {
                    new JsonAttribute("timestamp", "${date:universaltime=true:format=o}"),
                    new JsonAttribute("lvl",       "${level}"),
                    new JsonAttribute("msg",       "${message}"),
                    new JsonAttribute("logger",    "${logger}"),
                    new JsonAttribute("threadid",  "${threadid}", false),    // Skip quotes for integer-value
                }
            };

            var rule = new LoggingRule("*", elasticTarget);

            rule.EnableLoggingForLevel(LogLevel.Info);

            var config = new LoggingConfiguration();

            config.LoggingRules.Add(rule);

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

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

            logger.Info("Hello elasticsearch");

            LogManager.Flush();
        }
예제 #24
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);
            }
        }
        public FileLoggingConfigurator(string targetName, string[] namePatterns, string defaultFilePath)
        {
            _target = new FileTarget
            {
                Name = targetName,
            };

            _target.FileName = defaultFilePath;

            _rules = new LoggingRule[namePatterns.Length];
            for (var i = 0; i < namePatterns.Length; i++)
            {
                var rule = new LoggingRule
                {
                    LoggerNamePattern = namePatterns[i],
                    Final             = true,
                };

                rule.Targets.Add(_target);
                rule.Targets.Add(TorchUtils.GetWpfTarget());
                rule.EnableLoggingForLevels(LogLevel.Info, LogLevel.Off);
                _rules[i] = rule;
            }
        }
예제 #26
0
        static ProgramLogger()
        {
            var path = Path.Combine(Constant.DataDirectory, DirectoryName, Constant.Version);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var configuration = new LoggingConfiguration();

            using (var target = new FileTarget())
            {
                configuration.AddTarget("file", target);
                target.FileName = path.Replace(@"\", "/", StringComparison.Ordinal) + "/${shortdate}.txt";
#if DEBUG
                var rule = new LoggingRule("*", LogLevel.Debug, target);
#else
                var rule = new LoggingRule("*", LogLevel.Error, target);
#endif
                configuration.LoggingRules.Add(rule);
            }
            LogManager.Configuration = configuration;
        }
예제 #27
0
        private static LoggingRule RegisterAppFile(IAppFolderInfo appFolderInfo, string name, string fileName, int maxArchiveFiles)
        {
            var fileTarget = new NzbDroneFileTarget();

            fileTarget.Name                        = name;
            fileTarget.FileName                    = Path.Combine(appFolderInfo.GetLogFolder(), fileName);
            fileTarget.AutoFlush                   = true;
            fileTarget.KeepFileOpen                = false;
            fileTarget.ConcurrentWrites            = false;
            fileTarget.ConcurrentWriteAttemptDelay = 50;
            fileTarget.ConcurrentWriteAttempts     = 10;
            fileTarget.ArchiveAboveSize            = 1024000;
            fileTarget.MaxArchiveFiles             = maxArchiveFiles;
            fileTarget.EnableFileDelete            = true;
            fileTarget.ArchiveNumbering            = ArchiveNumberingMode.Rolling;
            fileTarget.Layout                      = FILE_LOG_LAYOUT;

            var loggingRule = new LoggingRule("*", LogLevel.Trace, fileTarget);

            LogManager.Configuration.AddTarget(name, fileTarget);
            LogManager.Configuration.LoggingRules.Add(loggingRule);

            return(loggingRule);
        }
예제 #28
0
        public static void AddTarget(Target target, LogLevel logLevel)
        {
            if (!loggingRules.TryGetValue(logLevel, out LoggingRule lr))
            {
                lr = new LoggingRule();
                foreach (var ll in LogLevel.AllLoggingLevels)
                {
                    if (ll >= logLevel)
                    {
                        lr.EnableLoggingForLevel(ll);
                    }
                    else
                    {
                        lr.DisableLoggingForLevel(ll);
                    }
                }
                lr.LoggerNamePattern = "*";
                LogConfiguration.LoggingRules.Add(lr);
                loggingRules[logLevel] = lr;
            }
            lr.Targets.Add(target);

            LogManager.Configuration = LogConfiguration;
        }
예제 #29
0
        static Log()
        {
            CurrentLogDirectory = Path.Combine(Constant.DataDirectory, DirectoryName, Constant.Version);
            if (!Directory.Exists(CurrentLogDirectory))
            {
                Directory.CreateDirectory(CurrentLogDirectory);
            }

            var configuration = new LoggingConfiguration();
            var target        = new FileTarget();

            configuration.AddTarget("file", target);

            // Adding CurrentCulture since this is user facing
            target.FileName = CurrentLogDirectory.Replace(@"\", "/", StringComparison.CurrentCulture) + "/${shortdate}.txt";
#if DEBUG
            var rule = new LoggingRule("*", LogLevel.Debug, target);
#else
            var rule = new LoggingRule("*", LogLevel.Info, target);
#endif
            configuration.LoggingRules.Add(rule);
            LogManager.Configuration = configuration;
            target.Dispose();
        }
예제 #30
0
        public NLogManager()
        {
            var config = new LoggingConfiguration();

            var consoleTarget = new ConsoleTarget();

            config.AddTarget("console", consoleTarget);

            var consoleRule = new LoggingRule("*", LogLevel.Trace, consoleTarget);

            config.LoggingRules.Add(consoleRule);

            var    fileTarget = new FileTarget();
            string folder     = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            fileTarget.FileName = Path.Combine(folder, "Log.txt");
            config.AddTarget("file", fileTarget);

            var fileRule = new LoggingRule("*", LogLevel.Warn, fileTarget);

            config.LoggingRules.Add(fileRule);

            LogManager.Configuration = config;
        }
예제 #31
0
        public void Setup()
        {
            var config   = new LoggingConfiguration();
            var loglevel = LogLevel.Debug;

            var layout = @"${message}";

            var cc = new ColoredConsoleTarget();

            var tt = new FileTarget();

            tt.FileName = @"C:\temp\mftLog.txt";

            config.AddTarget("cc", cc);
            config.AddTarget("tt", tt);

            cc.Layout = layout;

            var rule1 = new LoggingRule("*", loglevel, cc);

            config.LoggingRules.Add(rule1);
            var rule2 = new LoggingRule("*", loglevel, tt);

            config.LoggingRules.Add(rule2);

            LogManager.Configuration = config;

            Mfts = new Dictionary <string, string>();

            //   Mfts.Add("controller", @"D:\sync\MFTs\controller\$MFT");
            //   Mfts.Add("nfury", @"D:\sync\MFTs\nfury\$MFT");
            //    Mfts.Add("nromanoff", @"D:\sync\MFTs\nromanoff\$MFT");
            //     Mfts.Add("tdungan", @"..\..\TestFiles\tdungan\$MFT");
            Mfts.Add("blake", @"D:\sync\MFTs\blake\$MFT");
            //     Mfts.Add("other", @"..\..\TestFiles\$MFT");
        }
        /// <summary>
        /// Setups the logger with the <see cref="BufferedSumoLogicTarget"/> based on the given settings.
        /// </summary>
        /// <param name="messagesPerRequest">The maximum messages per request.</param>
        /// <param name="maxFlushInterval">The maximum flush interval, in milliseconds.</param>
        /// <param name="flushingAccuracy">The flushing accuracy, in milliseconds.</param>
        /// <param name="retryInterval">The retry interval, in milliseconds.</param>
        private void SetUpLogger(long messagesPerRequest, long maxFlushInterval, long flushingAccuracy, long retryInterval = 10000)
        {
            this.messagesHandler = new MockHttpMessageHandler();
            this.bufferedSumoLogicTarget = new BufferedSumoLogicTarget(null, this.messagesHandler);
            this.bufferedSumoLogicTarget.Url = "http://www.fakeadress.com";
            this.bufferedSumoLogicTarget.Layout = @"${level:upperCase=true}: ${message}";
            this.bufferedSumoLogicTarget.SourceName = "BufferedSumoLogicTargetTest";
            this.bufferedSumoLogicTarget.SourceName = "BufferedSumoLogicTargetTest";
            this.bufferedSumoLogicTarget.MessagesPerRequest = messagesPerRequest;
            this.bufferedSumoLogicTarget.MaxFlushInterval = maxFlushInterval;
            this.bufferedSumoLogicTarget.FlushingAccuracy = flushingAccuracy;
            this.bufferedSumoLogicTarget.RetryInterval = retryInterval;
            if (LogManager.Configuration == null)
            {
                LogManager.Configuration = new LoggingConfiguration();
            }

            LogManager.Configuration.AddTarget(this.bufferedSumoLogicTarget.SourceName, this.bufferedSumoLogicTarget);
            LoggingRule rule = new LoggingRule("BufferedSumoLogicTargetTest", LogLevel.Info, this.bufferedSumoLogicTarget);
            LogManager.Configuration.LoggingRules.Add(rule);
            LogManager.Configuration.Reload();
            LogManager.ReconfigExistingLoggers();
            this.logger = LogManager.GetLogger("BufferedSumoLogicTargetTest");
        }
예제 #33
0
        private static void SetupNLog()
        {
            var config = new LoggingConfiguration();
            var loglevel = LogLevel.Info;

            var layout = @"${message}";

            var consoleTarget = new ColoredConsoleTarget();

            config.AddTarget("console", consoleTarget);

            consoleTarget.Layout = layout;

            var rule1 = new LoggingRule("*", loglevel, consoleTarget);
            config.LoggingRules.Add(rule1);

            LogManager.Configuration = config;
        }