Inheritance: NLog.Targets.TargetWithLayoutHeaderAndFooter, ICreateFileParameters
Esempio n. 1
1
        private static void InitLogging()
        {
            var s_Config = new LoggingConfiguration();

            var s_ConsoleTarget = new ColoredConsoleTarget();
            s_Config.AddTarget("console", s_ConsoleTarget);

            s_ConsoleTarget.Layout = @"[${date:format=HH\:mm\:ss.fff}] ${logger} >> ${message}";

            var s_ConsoleRule = new LoggingRule("*", LogLevel.Trace, s_ConsoleTarget);
            s_Config.LoggingRules.Add(s_ConsoleRule);

            var s_FileTarget = new FileTarget();
            s_Config.AddTarget("file", s_FileTarget);

            s_FileTarget.FileName = "${basedir}/GrooveCaster.log";
            s_FileTarget.Layout = @"[${date:format=HH\:mm\:ss.fff}] ${logger} >> ${message}";
            s_FileTarget.ArchiveFileName = "${basedir}/GrooveCaster.{#}.log";
            s_FileTarget.ArchiveEvery = FileArchivePeriod.Day;
            s_FileTarget.ArchiveNumbering = ArchiveNumberingMode.Date;
            s_FileTarget.ArchiveDateFormat = "yyyMMdd";

            var s_FileRule = new LoggingRule("*", LogLevel.Trace, s_FileTarget);
            s_Config.LoggingRules.Add(s_FileRule);

            LogManager.Configuration = s_Config;
        }
 public static void LoadLoggerToLoggingConfig(LoggingConfiguration logConfig, IConfiguration Configuration,string sectionString)
 {
     var fileLoggerSection = Configuration.GetSection(sectionString).GetChildren();
     foreach (var logging in fileLoggerSection)
     {
         var target = new FileTarget()
         {
             FileName = logging["fileName"],
             Name = logging["name"],
             Layout = logging["layoutFormat"]
         };
         var minLevel = logging["minLevel"] != null ? LogLevel.FromString(logging["minLevel"]) : null;
         LoggingRule rule = null;
         if (minLevel != null)
         {
             rule = new LoggingRule(logging["namePattern"], minLevel, target);
         }
         else
         {
             rule = new LoggingRule(logging["namePattern"], target);
         }
         var useLevels = logging["logLevel"];
         if(string.IsNullOrWhiteSpace(useLevels) == false)
         {
             var levels = useLevels.Split(',');
             foreach (var level in levels)
             {
                 rule.EnableLoggingForLevel(LogLevel.FromString(level));
             }
         }
         logConfig.AddTarget(target);
         logConfig.LoggingRules.Add(rule);
     }
 }
Esempio n. 3
0
    private void InitializeLogger()
    {
        try
        {
            if (LogManager.Configuration != null)
            {
                return;
            }

            var target1 = new NLog.Targets.FileTarget();
            target1.FileName     = Path.Combine(GetTempFolder(), "Debug.log");
            target1.KeepFileOpen = false;
            target1.Layout       = "${longdate}|${level:uppercase=true}|${logger}|${message}|${exception:format=ToString}";
            var target2 = new NLog.Targets.DebuggerTarget();

            LogManager.Configuration = new NLog.Config.LoggingConfiguration();
            LogManager.Configuration.AddTarget("logFile", target1);
            LogManager.Configuration.AddTarget("debug", target2);
            LogManager.Configuration.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Trace, target1));
            LogManager.Configuration.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Trace, target2));
            LogManager.ReconfigExistingLoggers();
        }
        catch (Exception)
        {
        }
        finally
        {
            logger = LogManager.GetCurrentClassLogger();
        }
    }
Esempio n. 4
0
        public static void AddFileLogger(string filePath)
        {
            //Find the existing console logger target
            var existingTarget = NLog.LogManager.Configuration.FindTargetByName <TargetWithLayout>("console");

            if (existingTarget == null)
            {
                return;
            }

            var filename  = Path.GetFileNameWithoutExtension(filePath) + DateTime.Now.ToString("_yyyyMMdd_hhmmss");
            var basePath  = Path.GetDirectoryName(filePath);
            var extension = Path.GetExtension(filePath);

            filePath = FileSystem.BuildPath(basePath, filename + extension);

            //Create a new target that uses the same settings
            var fileTarget = new NLog.Targets.FileTarget("file")
            {
                AutoFlush    = true,
                Layout       = existingTarget.Layout,
                CreateDirs   = true,
                KeepFileOpen = true,
                FileName     = filePath,
            };

            AddTarget(fileTarget);
        }
Esempio n. 5
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);
        }
Esempio n. 6
0
        private void ConfigLogging()
        {
            var config = new LoggingConfiguration();

            var target = new DebuggerTarget
            {
                Layout = @"${date:format=HH\\:MM\\:ss} ${logger} ${message}"
            };

            var sqlTarget = new FileTarget
            {
                Layout = @"${date:format=HH\\:MM\\:ss} ${logger} ${message}",
                FileName = "sql.log"
            };

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

            config.AddTarget( "sql", sqlTarget );
            config.AddTarget( "debugger", target );
            config.LoggingRules.Add( sqlRule );
            config.LoggingRules.Add( rule );

            LogManager.Configuration = config;
        }
Esempio n. 7
0
        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
        }
Esempio n. 8
0
        public static LoggingConfiguration GetNLogConfig()
        {
            _config = new LoggingConfiguration();

            // Targets where to log to: File and Console
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName         = "/home/jol/logs/evo-demo-${shortdate}.log",
                Layout           = "${longdate} [${uppercase:${level}}] ${event-properties:item=EventId.Id}${newline}位置:${callsite:className=True:methodName=True:fileName=True:includeSourcePath=True:skipFrames=1}${newline}${message}${newline}${exception}${newline}",
                ArchiveAboveSize = 10485760,
                ArchiveNumbering = ArchiveNumberingMode.DateAndSequence,
                ConcurrentWrites = true,
                MaxArchiveFiles  = 100000,
                KeepFileOpen     = false,
            };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole")
            {
                Layout = "${longdate} [${uppercase:${level}}] ${event-properties:item=EventId.Id}${newline}位置:${callsite:className=True:methodName=True:fileName=True:includeSourcePath=True:skipFrames=1}${newline}${message}${newline}${exception}${newline}"
            };

            // Rules for mapping loggers to targets
            _config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole);
            _config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Debug, logfile);

            return(_config);
        }
Esempio n. 9
0
        /// <summary>
        ///     Initializes the NLog configuration
        /// </summary>
        /// <returns>A NLog logger</returns>
        private static Logger Initialize()
        {
            LogManager.Configuration = new LoggingConfiguration();

            FileTarget target = new FileTarget();
            target.Name = "file";
            target.Layout = new SimpleLayout(@"${longdate} | ${level:uppercase=true} | ${message}");
            target.FileName = new SimpleLayout(@"${specialfolder:ApplicationData}\TidyTabs\Debug.log");
            target.ArchiveFileName = new SimpleLayout(@"${specialfolder:ApplicationData}\TidyTabs\Debug_Archive_{#}.log");
            target.ArchiveEvery = FileArchivePeriod.Day;
            target.ArchiveNumbering = ArchiveNumberingMode.Rolling;
            target.MaxArchiveFiles = 3;
            target.KeepFileOpen = false;
            target.CreateDirs = true;
            target.Encoding = Encoding.UTF8;

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

            LogManager.Configuration.AddTarget("logfile", target);
            LogManager.Configuration.LoggingRules.Add(loggingRule);

            LogManager.ReconfigExistingLoggers();

            return LogManager.GetCurrentClassLogger();
        }
Esempio n. 10
0
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //NLog configuration alternative to NLog.config >>>>
            var config = new NLog.Config.LoggingConfiguration();

            FileTarget logfileTarget1 = new NLog.Targets.FileTarget("NLogExample.Model.ClassSon")
            {
                FileName = "NLogExample.Model.ClassSon.log"
            };
            FileTarget logfileTarget2 = new NLog.Targets.FileTarget("NLogExample.Model.ClassDaughter")
            {
                FileName = "NLogExample.Model.ClassDaughter.log"
            };

            //Format the output lines
            logfileTarget1.Layout = new NLog.Layouts.SimpleLayout("${longdate}|${uppercase:${level}}|" +
                                                                  "${ callsite:className=true:methodName=true} | ${message} ");
            logfileTarget2.Layout = new NLog.Layouts.SimpleLayout("${longdate}|${uppercase:${level}}|" +
                                                                  "${ callsite:className=true:methodName=true} | ${message} ");

            //!!LoggerNamePattern parameter is important to split the log strema into the files depending on the class instance!!
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfileTarget1, "NLogExample.Model.ClassSon");
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfileTarget2, "NLogExample.Model.ClassDaughter");

            NLog.LogManager.Configuration = config;
            //<<<< NLog configuration
        }
Esempio n. 11
0
        public static void Configure()
        {
            // Step 1. Create configuration object
            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}";
            fileTarget.FileName = "${basedir}/SimplePerformanceMeter.txt";
            fileTarget.Layout = "${message}";

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

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

            // Step 5. Activate the configuration
            LogManager.Configuration = config;
        }
Esempio n. 12
0
        public void FileAppenderCache_Allocate()
        {
            // Allocate on an Empty FileAppenderCache.
            FileAppenderCache emptyCache = FileAppenderCache.Empty;
            Assert.Throws<NullReferenceException>(() => emptyCache.AllocateAppender("file.txt"));

            // Construct a on non-empty FileAppenderCache.
            IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory;
            ICreateFileParameters fileTarget = new FileTarget();
            String tempFile = Path.Combine(
                    Path.GetTempPath(),
                    Path.Combine(Guid.NewGuid().ToString(), "file.txt")
            );
            
            // Allocate an appender.
            FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget);
            BaseFileAppender appender = cache.AllocateAppender(tempFile);

            //
            // Note: Encoding is ASSUMED to be Unicode. There is no explicit reference to which encoding will be used 
            //      for the file. 
            //

            // Write, flush the content into the file and release the file.
            // We need to release the file before invoking AssertFileContents() method.
            appender.Write(StringToBytes("NLog test string."));
            appender.Flush();
            appender.Close();
            // Verify the appender has been allocated correctly.
            AssertFileContents(tempFile, "NLog test string.", Encoding.Unicode);
        }
        protected virtual LoggingConfiguration SetupLogging(EndpointConfiguration endpointConfiguration)
        {
            var logDir = ".\\logfiles\\";

            Directory.CreateDirectory(logDir);

            var logFile = Path.Combine(logDir, endpointConfiguration.EndpointName + ".txt");

            if (File.Exists(logFile))
            {
                File.Delete(logFile);
            }

            var logLevel = "INFO";

            var nlogConfig = new LoggingConfiguration();

            var fileTarget = new FileTarget
            {
                FileName = logFile,
                Layout = "${longdate}|${level:uppercase=true}|${threadid}|${logger}|${message}${onexception:inner=${newline}${exception}${newline}${stacktrace:format=DetailedFlat}}"
            };

            nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", LogLevel.Warn, fileTarget) { Final = true });
            nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.FromString(logLevel), fileTarget));
            nlogConfig.AddTarget("debugger", fileTarget);
            NLogConfigurator.Configure(new object[] {fileTarget}, logLevel);
            return nlogConfig;
        }
Esempio n. 14
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>());
        }
Esempio n. 15
0
        public static void UseNLog(this IHost host)
        {
            var config = new LoggingConfiguration();

            var consoleTarget = new ColoredConsoleTarget();
            config.AddTarget("console", consoleTarget);

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

            var layout = @"${longdate}|${level:uppercase=true}|${threadid}|${logger}|${message}";

            consoleTarget.Layout = layout;
            fileTarget.FileName = @"${tempdir}\${processname}\Log\${processname}.${processinfo:Id}.log";
            fileTarget.ArchiveFileName = @"${tempdir}\${processname}\Log\${processname}.${processinfo:Id}.{###}.log";
            fileTarget.ArchiveEvery = FileArchivePeriod.Day;
            fileTarget.ArchiveAboveSize = 1024000;
            fileTarget.ArchiveNumbering = ArchiveNumberingMode.Rolling;
            fileTarget.MaxArchiveFiles = 10;
            fileTarget.ConcurrentWrites = false;
            fileTarget.KeepFileOpen = false;
            fileTarget.Layout = layout;

            config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Debug, consoleTarget));
            config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Info, fileTarget));

            LogManager.Configuration = config;

            host.Container.RegisterType(typeof (ILogger<>), typeof (NLogger<>));
        }
Esempio n. 16
0
    public static Logger BuildLogger()
    {
        var consoleTarget = new ColoredConsoleTarget
                                {
                                    Layout = "${message} ${exception:format=tostring}"
                                };

        var fileName = Path.Combine(Path.GetTempPath(), "NancyOnKayak", "WebsiteLog_${shortdate}.log");
        Console.WriteLine("Logging to:" + fileName);

        var fileTarget = new FileTarget
                             {
                                 FileName = fileName,
                                 Layout = "${longdate} ${message} ${exception:format=tostring}",
                                 AutoFlush = true,
                             };

        var config = new LoggingConfiguration
                         {
                             LoggingRules =
                                 {
                                     new LoggingRule("*", LogLevel.Debug, consoleTarget),
                                     new LoggingRule("*", LogLevel.Debug, fileTarget),
                                 }
                         };

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

        LogManager.Configuration = config;
        return LogManager.GetLogger("");
    }
Esempio n. 17
0
        private static void Configure(INewRelicConfig config)
        {
            config = config ?? NewRelicConfig.Instance;
            LoggingConfiguration loggingConfiguration = new LoggingConfiguration();
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget { Name = "Console" };
            loggingConfiguration.AddTarget("Console", consoleTarget);
            loggingConfiguration.LoggingRules.Add(new LoggingRule("*", ToNLogLevel(config.LogLevel), consoleTarget));

            // Store the LogLevel so it can be fetched by consumers
            LogLevel = config.LogLevel;

            if (config.LogFilePath.IsValidString() && config.LogFileName.IsValidString())
            {
                long archiveAboveSize = config.LogLimitInKiloBytes == 0 ? long.MaxValue : config.LogLimitInKiloBytes * 1024;
                FileTarget fileTarget = new FileTarget
                {
                    KeepFileOpen = true,
                    ConcurrentWrites = false,
                    FileName = Path.Combine(config.LogFilePath, config.LogFileName),
                    MaxArchiveFiles = 1,
                    ArchiveAboveSize = archiveAboveSize,
                    Name = "File",
                };

                loggingConfiguration.AddTarget("File", fileTarget);
                loggingConfiguration.LoggingRules.Add(new LoggingRule("*", ToNLogLevel(config.LogLevel), fileTarget));
            }

            NLogManager.Configuration = loggingConfiguration;
        }
        protected override LoggingConfiguration SetupLogging(EndpointConfiguration endpointConfiguration)
        {
            var logDir = ".\\logfiles\\";

            Directory.CreateDirectory(logDir);

            var logFile = Path.Combine(logDir, endpointConfiguration.EndpointName + ".txt");

            if (File.Exists(logFile))
            {
                File.Delete(logFile);
            }

            var logLevel = "ERROR";

            var nlogConfig = new LoggingConfiguration();

            var fileTarget = new FileTarget
            {
                FileName = logFile,
            };

            nlogConfig.LoggingRules.Add(new LoggingRule("Raven.*", LogLevel.Warn, fileTarget) { Final = true });
            nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.FromString(logLevel), fileTarget));
            nlogConfig.LoggingRules.Add(new LoggingRule("ServiceControl.ExternalIntegrations.*", LogLevel.Debug, fileTarget));
            nlogConfig.AddTarget("debugger", fileTarget);
            NLogConfigurator.Configure(new object[] { fileTarget }, logLevel);
            return nlogConfig;
        }
Esempio n. 19
0
        /* Configure the logger programmatically. */
        static NLoggerUtil()
        {
            var config = new LoggingConfiguration();
            string path = "GhostFactor.log";
            if (toDesktop)
                path = desktopPath + path;

            var target = new FileTarget
            {
                FileName = path
            };

            // Add a file target where all the log shall go to.
            config.AddTarget("file", target);

            // Add a rule that any information higher than debug goes to the file.
            var rule = new LoggingRule("*", LogLevel.Debug, target);
            config.LoggingRules.Add(rule);

            // Also log fatal logs to another file.
            string fatalPath = "GhostFactorFatal.log";
            if (toDesktop)
                fatalPath = desktopPath + fatalPath;
            var fatalTarget = new FileTarget()
            {
                FileName = fatalPath
            };
            var fatalRule = new LoggingRule("*", LogLevel.Fatal, fatalTarget);
            config.LoggingRules.Add(fatalRule);

            LogManager.Configuration = config;
        }
Esempio n. 20
0
        private static Logger CreateLogger()
        {
            var config = new LoggingConfiguration();

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

            fileTarget.FileName = "${basedir}\\AsteriskLog.txt";
            fileTarget.Layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss}: ${message}";
            fileTarget.ArchiveFileName = "${basedir}\\archives\\log.{#####}.txt";
            fileTarget.ArchiveAboveSize = 10240000;
            fileTarget.ArchiveNumbering = ArchiveNumberingMode.Sequence;

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

            var errorTarget = new FileTarget();
            config.AddTarget("errorfile", errorTarget);

            errorTarget.FileName = "${basedir}\\Errors.txt";
            errorTarget.Layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss}: ${message}";
            errorTarget.ArchiveFileName = "${basedir}\\archives\\log.{#####}.txt";
            errorTarget.ArchiveAboveSize = 10240000;
            errorTarget.ArchiveNumbering = ArchiveNumberingMode.Sequence;

            var errorsRule = new LoggingRule("*", LogLevel.Error, errorTarget);
            config.LoggingRules.Add(errorsRule);

            LogManager.Configuration = config;

            return LogManager.GetCurrentClassLogger();
        }
    private static void EnableFileLogging(RoslynInsertionToolOptions options)
    {
        var logConfig = LogManager.Configuration;

        // regular file logging
        var fileTarget = new NLog.Targets.FileTarget("file")
        {
            FileName = options.LogFileLocation, Layout = logConfig.Variables["VerboseLayout"]
        };

        logConfig.AddTarget(fileTarget);
        logConfig.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, fileTarget);

        // exception logging
        var exceptionFilter = new NLog.Filters.ConditionBasedFilter()
        {
            Condition = "length('${exception}') > 0", Action = NLog.Filters.FilterResult.Ignore
        };
        var exceptionFileTarget = new NLog.Targets.FileTarget("fileAsException")
        {
            FileName = options.LogFileLocation, Layout = logConfig.Variables["ExceptionVerboselayout"]
        };
        var rule = new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, exceptionFileTarget);

        rule.Filters.Add(exceptionFilter);
        logConfig.LoggingRules.Add(rule);

        logConfig.Reload();
    }
Esempio n. 22
0
        private static void Main(string[] args)
        {
            if (args.Length <= 0)
            {
                return;
            }

            var config = new LoggingConfiguration();
            var logfile = new FileTarget();
            var logdir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "HearthstoneTracker");
            logdir = Path.Combine(logdir, "logs");
            var logfilename = Path.Combine(logdir, "updater.${date:format=yyyy-MM-dd}.txt");
            logfile.FileName = logfilename;
            logfile.CreateDirs = true;
            logfile.MaxArchiveFiles = 7;
            logfile.ArchiveEvery = FileArchivePeriod.Day;
            logfile.ConcurrentWrites = true;
            logfile.Layout =
                "${longdate}|${level:uppercase=true}|thread:${threadid}|${logger}|${message}${onexception:inner=${newline}${exception:format=tostring}}";

            config.AddTarget("logfile", logfile);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, logfile));
            LogManager.Configuration = config;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new UpdateProgress(args));
        }
        /// <summary>
        /// Constructs an instance of DependencyRegistry
        /// </summary>
        public DependencyRegistry(ConfigSettings configSettings)
        {
            string logFileTemplate = configSettings.LogFileTemplate ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "default.log");
            string dataDirectory = configSettings.DataDirectory ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "configdata");
            LogLevel logLevel = GetMatchingLogLevelOrDefault(configSettings.LogLevel) ?? LogLevel.Info;

            For<IRepository<IJsonEntity<ConfigRoot>>>()
                .Singleton()
                .Use(new DurableMemoryRepository<ConfigRoot>(dataDirectory, new FileSystemFacade()));

            var config = new LoggingConfiguration();
            var fileTarget = new FileTarget();
            fileTarget.Name = "LogFile";
            fileTarget.FileName = logFileTemplate;
            config.AddTarget(fileTarget.Name, fileTarget);

            var loggingRule = new LoggingRule("*", logLevel, fileTarget);
            config.LoggingRules.Add(loggingRule);
            
            LogManager.Configuration = config;

            For<ILogger>()
                .Singleton()
                .Use(l => new LoggerAdapter(LogManager.GetLogger(GetType().Namespace)));

            // Ask StructureMap to always do property injection for certain properties
            // TODO: remove this?
            SetAllProperties(policy => policy.OfType<ILogger>()); 
        }
Esempio n. 24
0
    // ------------------------------------------
    //  Logs Management
    // ------------------------------------------

    protected void SetupLogging() {
      var path = ConfigManager.GetInstance().Find("debug.log-file", null);
      if (null == path) { return; }
      
      LoggingConfiguration config = new LoggingConfiguration();

      ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
      consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
      config.AddTarget("console", consoleTarget);

      FileTarget fileTarget = new FileTarget();
      fileTarget.FileName = path;
      fileTarget.Layout = "${message}";
      fileTarget.CreateDirs = true;
      config.AddTarget("file", fileTarget);

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

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

      LoggingRule rule3 = new LoggingRule("*", LogLevel.Warn, consoleTarget);
      config.LoggingRules.Add(rule3);

      LoggingRule rule4 = new LoggingRule("*", LogLevel.Warn, fileTarget);
      config.LoggingRules.Add(rule4);

      // Ready
      LogManager.ReconfigExistingLoggers();
      LogManager.Configuration = config;
      Host.Log(this, "STARTING LOGGING:" + fileTarget.FileName);
    }
Esempio n. 25
0
        public static void TargetFile(string fileName, bool verbose)
        {
            var target = new FileTarget { Layout = LayoutFormat, FileName = fileName };

            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, verbose ? LogLevel.Debug : LogLevel.Info);
            LogManager.ReconfigExistingLoggers();
        }
Esempio n. 26
0
        private void ConfigureSharedFile(string mode, string fileName)
        {
            var modes = mode.Split('|');

            FileTarget ft = new FileTarget();
            ft.FileName = "${basedir}/" + fileName;
            ft.Layout = "${message}";
            ft.KeepFileOpen = true;
            ft.OpenFileCacheTimeout = 10;
            ft.OpenFileCacheSize = 1;
            ft.LineEnding = LineEndingMode.LF;
            ft.ForceMutexConcurrentWrites = modes.Length == 2 && modes[1] == "mutex" ? true : false;

            var name = "ConfigureSharedFile_" + mode.Replace('|', '_') + "-wrapper";

            switch (modes[0])
            {
                case "async":
                    SimpleConfigurator.ConfigureForTargetLogging(new AsyncTargetWrapper(ft, 100, AsyncTargetWrapperOverflowAction.Grow) { Name = name }, LogLevel.Debug);
                    break;

                case "buffered":
                    SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100) { Name = name }, LogLevel.Debug);
                    break;

                case "buffered_timed_flush":
                    SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100, 10) { Name = name }, LogLevel.Debug);
                    break;

                default:
                    SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
                    break;
            }
        }
Esempio n. 27
0
        public static void EnableErrorLogging()
        {
            if (IsErrorLoggingEnabled) {
                return;
            }

            LoggingConfiguration config = LogManager.Configuration;
            FileTarget errorTarget = new FileTarget() {
                Name = "fileError",
                Layout = "-------------- ${level} (${longdate}) --------------${newline}"
                    + "${newline}"
                    + "Call Site: ${callsite}${newline}"
                    + "Type: ${exception:format=Type}${newline}"
                    + "Message: ${exception:format=Message}${newline}"
                    + "Stack Trace: ${exception:format=StackTrace}${newline}"
                    + "${newline}",
                FileName = BaseLogDirectory + @"\MobiBot\Error\error.log",
                ArchiveFileName = BaseLogDirectory + @"\MobiBot\Error\error.{###}.txt",
                ArchiveEvery = FileArchivePeriod.Day,
                ArchiveNumbering = ArchiveNumberingMode.Rolling,
                MaxArchiveFiles = 30,
                NetworkWrites = true,
                KeepFileOpen = true
            };

            config.AddTarget(errorTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Error, errorTarget));
            IsErrorLoggingEnabled = true;
        }
Esempio n. 28
0
        public void ConfigureNlog(Logger logger)
        {
            FileTarget target = new FileTarget();

            target.FileName = "${basedir}\\logs\\ICtrl.Log_${date:format=ddMMyyyy}.txt";
            target.KeepFileOpen = false;
            target.Encoding = "windows-1251";
            target.Layout = "${date:format=HH\\:mm\\:ss.fff}|${level:padding=5:uppercase=true}|${message}";

            AsyncTargetWrapper wrapper = new AsyncTargetWrapper();

            wrapper.WrappedTarget = target;
            wrapper.QueueLimit = 5000;
            wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block;

            logOn = GetLogLevel();

            switch (logOn)
            {
                case 1:
                    NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Info);
                    break;
                default:
                    NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Off);
                    break;
            }
        }
Esempio n. 29
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.EnableFileDelete = true;
            fileTarget.MaxArchiveFiles = 7;
            fileTarget.ArchiveEvery = FileArchivePeriod.Minute;
            
            // 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);
        }
Esempio n. 30
0
        public void SimpleFileTest1()
        {
            string tempFile = Path.GetTempFileName();
            try
            {
                FileTarget ft = new FileTarget();
                ft.FileName = SimpleLayout.Escape(tempFile);
                ft.LineEnding = LineEndingMode.LF;
                ft.Layout = "${level} ${message}";
                ft.OpenFileCacheTimeout = 0;

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);

                logger.Debug("aaa");
                logger.Info("bbb");
                logger.Warn("ccc");
                LogManager.Configuration = null;
                AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8);
            }
            finally
            {
                if (File.Exists(tempFile))
                    File.Delete(tempFile);
            }
        }
Esempio n. 31
0
		private void BuildNlogConfig()
		{
		      	LoggingConfiguration config = new LoggingConfiguration(); 
	         
	        	// Create targets 
	         	ConsoleTarget consoleTarget = new ConsoleTarget(); 
	        	config.AddTarget("console", consoleTarget); 
	         
	        	FileTarget fileTarget = new FileTarget(); 
	        	config.AddTarget("file", fileTarget); 
		        
		        //memoryTarget = new MemoryTarget();
		        //config.AddTarget("memory", memoryTarget);
		        
		         // define layout
		        consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${level} ${logger} ${message}"; 
		        fileTarget.FileName = System.IO.Path.Combine(System.IO.Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "monotorrent"), "monotorrent.log"); 
		        fileTarget.Layout = "${level} ${stacktrace} ${message}"; 
		        //memoryTarget.Layout = "${date:format=HH\\:MM\\:ss} ${level} ${logger} ${message}";
		        
		        // define rules 
		        LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget); 
		        config.LoggingRules.Add(rule1); 
		        LoggingRule rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget); 
		        config.LoggingRules.Add(rule2); 
		        //LoggingRule rule3 = new LoggingRule("*", LogLevel.Debug, fileTarget);
		        //config.LoggingRules.Add(rule3);
			LogManager.Configuration = config; 
		}
        private void ConfigureLogging()
        {
            var fileTarget = new FileTarget {
                FileName = Path.Combine(GetLogFolder(), "log.xml"),
                ArchiveFileName = "log_{#####}.xml",
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
                ArchiveAboveSize = 1024*1024,
                Layout = new Log4JXmlEventLayout()
            };

            var config = new LoggingConfiguration();
            config.AddTarget("file", fileTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget));

            var debuggerTarget = new DebuggerTarget();
            config.AddTarget("debugger", debuggerTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, debuggerTarget));

            if (Debugger.IsAttached) {
                var udpTarget = new NetworkTarget {
                    Address = "udp4://localhost:962",
                    Layout = new Log4JXmlEventLayout()
                };
                config.AddTarget("udp", udpTarget);
                config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, udpTarget));
            }

            LogManager.Configuration = config;

            PresentationTraceSources.DataBindingSource.Listeners.Add(new NLogTraceListener());
        }
Esempio n. 33
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MutexMultiProcessFileAppender" /> class.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="target">The file target.</param>
        public MutexMultiProcessFileAppender(string fileName, FileTarget target)
            : base(fileName)
        {
            try
            {
                this.mutex = new Mutex(false, GetMutexName(fileName));
                this.file = target.CreateFileStream(fileName, true, true);
            }
            catch
            {
                if (this.mutex != null)
                {
                    this.mutex.Close();
                    this.mutex = null;
                }

                if (this.file != null)
                {
                    this.file.Close();
                    this.file = null;
                }

                throw;
            }
        }
Esempio n. 34
0
        public override void Load()
        {
            // log layout format
            var layout = "${date:format=hh\\:mm\\:ss tt} ${pad:padding=6:inner=${level:uppercase=true}} ${message} ${exception:separator=\r\n:format=message,type,method,stackTrace:maxInnerExceptionLevel=10:innerExceptionSeparator=\r\n:innerFormat=message,type,method,stackTrace}";

            // initialize logging configuration
            var config = new LoggingConfiguration();

            // create debugger target
            var debuggerTarget = new DebuggerTarget();
            debuggerTarget.Layout = layout;
            config.AddTarget("console", debuggerTarget);
            config.LoggingRules.Add(new LoggingRule("*", logLevel, WrapAsync(debuggerTarget)));

            // create file target
            var fileTarget = new FileTarget() { AutoFlush = false };
            fileTarget.Layout = layout;
            fileTarget.FileName = Path.Combine(this.directory, "BitSharp.log");
            fileTarget.DeleteOldFileOnStartup = true;
            config.AddTarget("file", fileTarget);
            config.LoggingRules.Add(new LoggingRule("*", logLevel, WrapAsync(fileTarget)));

            // activate configuration and bind
            LogManager.Configuration = config;
        }
Esempio n. 35
0
        private static Logger SetupNLog(NLogConfigurationApi config)
        {
            var logDirectory = string.IsNullOrEmpty(config.LogDirectory) ?
                "${basedir}/Logs" :
                config.LogDirectory;

            var fileTarget = new FileTarget
            {
                Name = "FileTarget",
                Layout = "${message}",
                ConcurrentWrites = false,
                FileName = new SimpleLayout(Path.Combine(logDirectory, "current.log")),
                ArchiveEvery = config.ArchivePeriod,
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
                MaxArchiveFiles = config.MaxArchiveFiles,
                ArchiveFileName = new SimpleLayout(Path.Combine(logDirectory,"archive/{####}.log"))
            };
            var asyncWrapper = new AsyncTargetWrapper(fileTarget)
            {
                Name = "AsyncWrapper"
            };

            var loggingConfiguration = new LoggingConfiguration();
            loggingConfiguration.AddTarget(LoggerName, asyncWrapper);
            loggingConfiguration.LoggingRules.Add(new LoggingRule("*", LevelToNLogLevel(config.MinimumLogLevel), asyncWrapper));

            LogManager.Configuration = loggingConfiguration;

            return LogManager.GetLogger(LoggerName);
        }
Esempio n. 36
0
        private static ILoggerFactory GetNLogLoggerFactory()
        {
            LoggingConfiguration loggerConfig = new NLog.Config.LoggingConfiguration();
            FileTarget           fileTarget   = new NLog.Targets.FileTarget()
            {
                Name     = "logfile",
                FileName = "log.txt",
                Layout   = "${longdate}|${level:uppercase=true}|${logger}|${event-context:item=EventId}|${message}|${ndc}"
            };

            loggerConfig.AddTarget(fileTarget);
            loggerConfig.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Info, fileTarget));
            //NLogLoggerFactory test = new NLogLoggerFactory(new NLogLoggerProvider(new NLogProviderOptions()));
            NLogLoggerFactory   logLoggerFactory = new NLogLoggerFactory();
            NLogProviderOptions op = new NLogProviderOptions
            {
                CaptureMessageProperties = true,
                CaptureMessageTemplates  = true,
                EventIdSeparator         = "|",
                IgnoreEmptyEventId       = false,
                IncludeScopes            = true,
                //ParseMessageTemplates = true
                //ShutdownOnDispose = true
            };

            NLogLoggerProvider p = new NLogLoggerProvider(op, loggerConfig.LogFactory);

            logLoggerFactory.AddProvider(p);
            return(logLoggerFactory);
            //loggerFactory.AddNLog(new NLog.LogFactory(loggerConfig));
        }
Esempio n. 37
0
        private void ConfigureSharedFile(string mode)
        {
            FileTarget ft = new FileTarget();
            ft.FileName = "${basedir}/file.txt";
            ft.Layout = "${threadname} ${message}";
            ft.KeepFileOpen = true;
            ft.OpenFileCacheTimeout = 10;
            ft.OpenFileCacheSize = 1;
            ft.LineEnding = LineEndingMode.LF;

            switch (mode)
            {
                case "async":
                    SimpleConfigurator.ConfigureForTargetLogging(new AsyncTargetWrapper(ft, 100, AsyncTargetWrapperOverflowAction.Grow), LogLevel.Debug);
                    break;

                case "buffered":
                    SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100), LogLevel.Debug);
                    break;

                case "buffered_timed_flush":
                    SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100, 10), LogLevel.Debug);
                    break;

                default:
                    SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
                    break;
            }
        }
Esempio n. 38
0
        public WPFLogger(MainWindow userForm)
        {
            form = userForm;
            //Cleanup old log
            if (File.Exists(Path.Combine(Directory.GetParent(App.GetExecutablePath()).FullName, "CaptureLog.txt")))
            {
                File.Delete(Path.Combine(Directory.GetParent(App.GetExecutablePath()).FullName, "CaptureLog.txt"));
            }

            var             LoggingConfig = new NLog.Config.LoggingConfiguration();
            FileVersionInfo v             = FileVersionInfo.GetVersionInfo(App.GetExecutablePath());
            var             logfile       = new NLog.Targets.FileTarget("logfile")
            {
                FileName                = "${specialfolder:folder=ApplicationData:cached=true}/AmongUsCapture/logs/latest.log",
                ArchiveFileName         = "${specialfolder:folder=ApplicationData:cached=true}/AmongUsCapture/logs/{#}.log",
                ArchiveNumbering        = ArchiveNumberingMode.Date,
                Layout                  = "${time:universalTime=True} | ${message}",
                MaxArchiveFiles         = 5,
                ArchiveOldFileOnStartup = true,
                ArchiveDateFormat       = "yyyy-MM-dd HH_mm_ss",
                Header                  = $"Capture version: {v.FileMajorPart}.{v.FileMinorPart}.{v.FileBuildPart}.{v.FilePrivatePart}\n",
                Footer                  = $"\nCapture version: {v.FileMajorPart}.{v.FileMinorPart}.{v.FileBuildPart}.{v.FilePrivatePart}"
            };

            LoggingConfig.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = LoggingConfig;
            logger = LogManager.GetLogger("WPFLogger");
        }
Esempio n. 39
0
        public static void Configure()
        {
            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget()
            {
                FileName = "file.txt", Name = "logfile"
            };

            logfile.Layout = "Level        : ${level} ${newline}When         : ${longdate} ${newline}Message      : ${message} ${newline}Machine Name : ${machinename} ${newline}Stack Trace  : ${stacktrace} ${newline} ";


            //            layout type = "log4net.Layout.PatternLayout" >
            //< IgnoresException value = "False" />

            // ...


            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Error, logfile));
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logfile));

            logfile.ArchiveEvery      = FileArchivePeriod.Day;
            logfile.ArchiveNumbering  = ArchiveNumberingMode.Rolling;
            logfile.ConcurrentWrites  = true;
            logfile.KeepFileOpen      = false;
            logfile.ArchiveDateFormat = "yyyyMMdd";

            LogManager.Configuration = config;
        }
Esempio n. 40
0
        public static void Configure()
        {
            var config = new LoggingConfiguration();
            var fileTarget = new FileTarget();

            fileTarget.FileName = Path.Combine(Util.get_log_folder(), "btnet_log.txt");
            fileTarget.ArchiveNumbering = ArchiveNumberingMode.Date;
            fileTarget.ArchiveEvery = FileArchivePeriod.Day;
            config.AddTarget("File", fileTarget);

            var mailTarget = new MailTarget
            {
                UseSystemNetMailSettings = true,
                To = Util.get_setting("ErrorEmailTo", ""),
                From = Util.get_setting("ErrorEmailFrom", ""),
                Subject = "BTNET Error Notification",
                Layout = "${machinename}${newline} ${date} ${newline} ${newline} ${message} ${newline}  ${exception} ${newline}"
            };
            config.AddTarget("Mail", mailTarget);

            //Turn logging on/off based on the LogEnabled setting
            var logLevel = Util.get_setting("LogEnabled", "1") == "1" ? LogLevel.Trace: LogLevel.Off;
            config.LoggingRules.Add(new LoggingRule("*", logLevel, fileTarget));

            var emailLogLevel = Util.get_setting("ErrorEmailEnabled", "1") == "1" ? LogLevel.Fatal : LogLevel.Off;
            config.LoggingRules.Add(new LoggingRule("*", emailLogLevel, mailTarget));

            LogManager.Configuration = config;
        }
Esempio n. 41
0
File: Startup.cs Progetto: lx223/Q3
        private void initLog()
        {
            var path = HostingEnvironment.MapPath("~/App_Data");

            var config = new LoggingConfiguration();

            var fileTarget = new FileTarget()
            {
                FileName = Path.Combine(path, "activity.log"),
                ArchiveFileName = Path.Combine(path, "activity.{#####}.log"),
                ArchiveAboveSize = 1024 * 1024,
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
                ConcurrentWrites = false,
                Layout = "${longdate} | ${level} | ${logger} | ${message} ${exception:format=tostring}",
                AutoFlush = true,
                MaxArchiveFiles = 50
            };

            config.AddTarget("file", fileTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget));

            var traceTarget = new TraceTarget() { Layout = "${level} | ${logger} | ${message} ${exception:format=tostring}" };
            config.AddTarget("trace", traceTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, traceTarget));

            LogManager.Configuration = config;
        }
Esempio n. 42
0
        public void InitTargetFile(Session session)
        {
            //string dataTime = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");


            //":" in Path is not possible by windows
            // _filePath = _homeDir + "\\" +"LoggingData" + @"\${date:format=dd-MM-yyyy HH\:mm\:ss}.json";

            /*
             * Set and hold the file Path by every runing
             */

            var filePath = Path.Combine(_homeDir, "LoggingData", session.Name + ".json");
            var logfile  = new NLog.Targets.FileTarget("JsonLogger");


            //set the layout of json format, MaxRecursionLimit can make sub object serialized, too!!!
            var jsonLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("session",         session.Name),
                    new JsonAttribute("time",            "${longdate}"),
                    new JsonAttribute("level",           "${level:upperCase=true}"),
                    new JsonAttribute("message",         "${message}"),
                    new JsonAttribute("eventProperties", new JsonLayout
                    {
                        IncludeAllProperties = true,
                        MaxRecursionLimit    = 10
                    },                                   false)
                }
            };

            // set the attribute of the new target
            logfile.Name     = "JsonLogger";
            logfile.FileName = filePath;
            logfile.Layout   = jsonLayout;


            // add the new target to current configuration
            NLog.LogManager.Configuration.AddTarget(logfile);

            // create new rule
            var rule = new LoggingRule("JsonLogger", LogLevel.Trace, logfile);

            NLog.LogManager.Configuration.LoggingRules.Add(rule);

            /*
             * reload the new configuration. It's very important here.
             * Do not use NLog.LogManager.Configuration = config;
             * This will destory current configuration.
             * So just add and reload.
             */
            LogManager.Configuration.Reload();


            // get the specified Logger
            _logger = NLog.LogManager.GetLogger("JsonLogger");
        }
Esempio n. 43
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;
    }
Esempio n. 44
0
        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;
        }
Esempio n. 45
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");
        }
Esempio n. 46
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;
        }
Esempio n. 47
0
        public void SetupLoggingConfig()
        {
            var             LoggingConfig = new NLog.Config.LoggingConfiguration();
            FileVersionInfo v             = FileVersionInfo.GetVersionInfo(App.GetExecutablePath());
            var             logfile       = new NLog.Targets.FileTarget("logfile")
            {
                FileName                = "${specialfolder:folder=ApplicationData:cached=true}/AmongUsCapture/logs/latest.log",
                ArchiveFileName         = "${specialfolder:folder=ApplicationData:cached=true}/AmongUsCapture/logs/{#}.log",
                ArchiveNumbering        = ArchiveNumberingMode.Date,
                Layout                  = "${time:universalTime=True}|${level:uppercase=true}|${logger}|${message}",
                MaxArchiveFiles         = 100,
                ArchiveOldFileOnStartup = true,
                ArchiveDateFormat       = "yyyy-MM-dd HH_mm_ss",
                Header                  = $"Capture version: {v.FileMajorPart}.{v.FileMinorPart}.{v.FileBuildPart}.{v.FilePrivatePart}\n",
                Footer                  = $"\nCapture version: {v.FileMajorPart}.{v.FileMinorPart}.{v.FileBuildPart}.{v.FilePrivatePart}"
            };

            LoggingConfig.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = LoggingConfig;
        }
Esempio n. 48
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();
    }
Esempio n. 49
0
        public static void Initialize(string logFile, MsixHeroLogLevel minLogLevel = MsixHeroLogLevel.Debug, MsixHeroLogLevel maxLogLevel = MsixHeroLogLevel.Fatal)
        {
            if (string.IsNullOrEmpty(logFile))
            {
                throw new ArgumentNullException(nameof(logFile));
            }

            var config = new NLog.Config.LoggingConfiguration();

            var logfile = new NLog.Targets.FileTarget
            {
                FileName = logFile,
                Header   = GetHeader(),
                Layout   = "${longdate}\t${level:uppercase=true}\t${logger}\t${message}\t${exception:format=tostring}"
            };

            config.AddRule(Convert(minLogLevel), Convert(maxLogLevel), logfile);
            config.AddRule(Convert(minLogLevel), Convert(maxLogLevel), new ConsoleTarget());

            NLog.LogManager.Configuration = config;
        }
Esempio n. 50
0
        // DiscordSocketClient and CommandService are injected automatically from the IServiceProvider
        public LoggingService(DiscordSocketClient discord, CommandService commands)
        {
            _logDirectory = Path.Combine(AppContext.BaseDirectory, "logs");

            _discord  = discord;
            _commands = commands;

            _discord.Log  += OnLogAsync;
            _commands.Log += OnLogAsync;

            var logConfig = new NLog.Config.LoggingConfiguration();

            var logFile = new NLog.Targets.FileTarget("logFile")
            {
                FileName = _logFile, ArchiveEvery = FileArchivePeriod.Day
            };
            var logConsole = new NLog.Targets.ConsoleTarget("logConsole");

            logConfig.AddRule(LogLevel.Info, LogLevel.Fatal, logFile);
            logConfig.AddRule(LogLevel.Info, LogLevel.Fatal, logConsole);

            NLog.LogManager.Configuration = logConfig;
        }
Esempio n. 51
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            Button button = FindViewById <Button>(Resource.Id.btnTest);

            var externalFolder = GetExternalFilesDir(null);

            var config = new NLog.Config.LoggingConfiguration();

            var logfile = new NLog.Targets.FileTarget()
            {
                FileName = externalFolder + "/afile.log", Name = "logfile"
            };

            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logfile));

            var consoleView   = FindViewById <TextView>(Resource.Id.resultsView);
            var consoleTarget = new MyFirstTarget(consoleView, this);

            consoleTarget.Layout = NLog.Layouts.Layout.FromString("${longdate} | ${message}");
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, consoleTarget));

            LogManager.Configuration = config;

            logger.Trace("Logger Started");

            button.Click += delegate
            {
                TestTransaction();
            };

            CheckThisIsDefault();
        }
Esempio n. 52
0
        static void Main(string[] args)
        {
            /* Set up logging configuration */
            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                Layout   = @"[${longdate}] [${level}] [${callsite}:${callsite-linenumber}] ${message} ${exception}",
                FileName = Settings.outdir + "\\SWDecoder_" + Settings.epoch + ".log"
            };

            var logconsole = new ColoredConsoleTarget("logconsole")
            {
                Layout = @"[${longdate}] [${level}] ${message} ${exception}"
            };
            var lognullstream = new NLog.Targets.NullTarget();

            config.AddRule(LogLevel.Info, LogLevel.Fatal, logfile, "SWDecoder*"); // Only log from the SWDecoder logger and ignore libraries
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole, "SWDecoder*");
            NLog.LogManager.Configuration = config;
            Console.WriteLine(" _____       _     ______                   _           ");
            Console.WriteLine("/  ___|     | |    |  _  \\                 | |          ");
            Console.WriteLine("\\ `--.  ___ | |_ __| | | |___  ___ ___   __| | ___ _ __ ");
            Console.WriteLine(" `--. \\/ _ \\| | '__| | | / _ \\/ __/ _ \\ / _` |/ _ \\ '__|");
            Console.WriteLine("/\\__/ / (_) | | |  | |/ /  __/ (_| (_) | (_| |  __/ |   ");
            Console.WriteLine("\\____/ \\___/|_|_|  |___/ \\___|\\___\\___/ \\__,_|\\___|_|   ");
            Console.WriteLine("                                                        ");
            Console.WriteLine("======== A tool to convert compressed base64 compressed strings to plaintext ============");
            CommandLine.Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(o =>
            {
                Settings.infile = Path.GetFullPath(o.InputPath.TrimEnd('\\'));
                Settings.outdir = Path.GetFullPath(o.OutputPath.TrimEnd('\\'));
            })
            .WithNotParsed(HandleParseError);
            _log.Info("Reading the input file");
            FileRead.readFile();
        }
Esempio n. 53
0
        public MainWindow()
        {
            InitializeComponent();
            //Sets default properties rows from project settings
            settingshandler = new SettingsHandler(sp_settings);

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

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

            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logconsole));
            config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, logfile));

            NLog.LogManager.Configuration = config;
            //Logger logger = NLog.LogManager.GetCurrentClassLogger();
            #endregion

            logger.Info("start");

            //checking net status
            indikacenetu();
            Connection.CheckingConnection();

            GetterInit(settingshandler.getUrlTB());

            //int Desc;
            //if (!InternetGetConnectedState(out Desc, 0))
            //    lb_status.Content = "No connection";
        }
        public static void ConfigureNLog()
        {
            try
            {
                var config      = new NLog.Config.LoggingConfiguration();
                var minLogLevel = LogLevel.FromString(Environment.GetEnvironmentVariable("LOGGING_MIN_LEVEL"));
                var maxLogLevel = LogLevel.FromString(Environment.GetEnvironmentVariable("LOGGING_MAX_LEVEL"));

                //console logging
                var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
                config.AddRule(minLogLevel, maxLogLevel, logconsole);

                if (Globals.EnableFileLogging)
                {
                    // file loggin
                    var logfile = new NLog.Targets.FileTarget("logfile")
                    {
                        FileName = "logfile.log"
                    };
                    config.AddRule(minLogLevel, maxLogLevel, logfile);
                }


                if (Globals.EnableDBLogging)
                {
                    //db loggin
                    var logdb = new NLog.Targets.DatabaseTarget("logdb");
                    logdb.CommandText      = @" insert into [Log] (MachineName, Logged, Level, Message,Logger, Properties, Callsite, Exception) 
                    values (@MachineName, @Logged, @Level, @Message, @Logger, @Properties, @Callsite, @Exception);";
                    logdb.CommandType      = System.Data.CommandType.Text;
                    logdb.ConnectionString = Globals.SkillbaseConnectionString;
                    logdb.Parameters.Add(new DatabaseParameterInfo()
                    {
                        Name = "@MachineName", Layout = "${machinename}"
                    });
                    logdb.Parameters.Add(new DatabaseParameterInfo()
                    {
                        Name = "@Logged", Layout = "${date}"
                    });
                    logdb.Parameters.Add(new DatabaseParameterInfo()
                    {
                        Name = "@Level", Layout = "${level}"
                    });
                    logdb.Parameters.Add(new DatabaseParameterInfo()
                    {
                        Name = "@Message", Layout = "${message}"
                    });
                    logdb.Parameters.Add(new DatabaseParameterInfo()
                    {
                        Name = "@Logger", Layout = "${logger}"
                    });
                    logdb.Parameters.Add(new DatabaseParameterInfo()
                    {
                        Name = "@Properties", Layout = "${all-event-properties:separator=|}"
                    });
                    logdb.Parameters.Add(new DatabaseParameterInfo()
                    {
                        Name = "@Callsite", Layout = "${callsite}"
                    });
                    logdb.Parameters.Add(new DatabaseParameterInfo()
                    {
                        Name = "@Exception", Layout = "${exception:tostring}"
                    });

                    config.AddRule(minLogLevel, maxLogLevel, logdb);
                }


                // Apply config
                NLog.LogManager.Configuration = config;
            }
            catch (Exception)
            {
            }
        }
Esempio n. 55
0
        // TODO remove forced mode checkbox?

        public BmpMain()
        {
            InitializeComponent();
            SetupCommands();

            this.UpdatePerformance();

            BmpUpdate update = new BmpUpdate();

            if (!Program.programOptions.DisableUpdate)
            {
                updateResult = update.ShowDialog();
                if (updateResult == DialogResult.Yes)
                {
                    updateTitle  = update.version.updateTitle;
                    updateText   = update.version.updateText;
                    updateResult = DialogResult.Yes;
                }
            }
            this.Text = update.version.ToString();

            // Clear local orchestra
            InfoTabs.TabPages.Remove(localOrchestraTab);

            FFXIV.findProcessRequest += delegate(Object o, EventArgs empty) {
                this.Invoke(t => t.FindProcess());
            };

            FFXIV.findProcessError += delegate(Object o, BmpHook.ProcessError error) {
                this.Invoke(t => t.ErrorProcess(error));
            };

            FFXIV.hotkeys.OnFileLoad += delegate(Object o, EventArgs empty) {
                this.Invoke(t => t.Hotkeys_OnFileLoad(FFXIV.hotkeys));
            };
            FFXIV.hook.OnKeyPressed     += Hook_OnKeyPressed;
            FFXIV.memory.OnProcessReady += delegate(object o, Process proc) {
                this.Log(string.Format("[{0}] Process scanned and ready.", proc.Id));
            };
            FFXIV.memory.OnProcessLost += delegate(object o, EventArgs arg) {
                this.Log("Attached process exited.");
            };
            FFXIV.memory.OnChatReceived += delegate(object o, ChatLogItem item) {
                this.Invoke(t => t.Memory_OnChatReceived(item));
            };
            FFXIV.memory.OnPerformanceChanged += delegate(object o, List <uint> ids) {
                this.Invoke(t => t.LocalOrchestraUpdate((o as FFXIVMemory).GetActorItems(ids)));
            };
            FFXIV.memory.OnPerformanceReadyChanged += delegate(object o, bool performance) {
                this.Invoke(t => t.Memory_OnPerformanceReadyChanged(performance));
            };
            FFXIV.memory.OnCurrentPlayerJobChange += delegate(object o, CurrentPlayerResult res) {
                this.Invoke(t => t.Memory_OnCurrentPlayerJobChange(res));
            };
            FFXIV.memory.OnCurrentPlayerLogin += delegate(object o, CurrentPlayerResult res) {
                string format = string.Format("Character [{0}] logged in.", res.CurrentPlayer.Name);
                this.Log(format);

                this.Invoke(t => t.UpdatePerformance());
            };
            FFXIV.memory.OnCurrentPlayerLogout += delegate(object o, CurrentPlayerResult res) {
                string format = string.Format("Character [{0}] logged out.", res.CurrentPlayer.Name);
                this.Log(format);
            };
            FFXIV.memory.OnPartyChanged += delegate(object o, PartyResult res) {
                this.Invoke(t => t.LocalOrchestraUpdate());
            };

            Player.OnStatusChange += delegate(object o, PlayerStatus status) {
                this.Invoke(t => t.UpdatePerformance());
            };

            Player.OnSongSkip  += OnSongSkip;
            Player.OnMidiLyric += OnMidiLyric;

            Player.OnMidiStatusChange += OnPlayStatusChange;
            Player.OnMidiStatusEnded  += OnPlayStatusEnded;

            Player.OnMidiNote  += OnMidiVoice;
            Player.OffMidiNote += OffMidiVoice;

            Player.Player.OpenInputDevice(Settings.GetMidiInput().name);

            Settings.OnMidiInputChange += delegate(object o, MidiInput input) {
                Player.Player.CloseInputDevice();
                if (input.id != -1)
                {
                    Player.Player.OpenInputDevice(input.name);
                    Log(string.Format("Switched to {0} ({1})", input.name, input.id));
                }
            };
            Settings.OnKeyboardTest += delegate(object o, EventArgs arg) {
                foreach (FFXIVKeybindDat.Keybind keybind in FFXIV.hotkeys.GetPerformanceKeybinds())
                {
                    FFXIV.hook.SendSyncKeybind(keybind);
                    Thread.Sleep(100);
                }
            };

            Settings.OnForcedOpen += delegate(object o, bool open) {
                this.Invoke(t => t.UpdatePerformance());
            };

            chordNotes            = new NoteChordSimulation <BmpPlayer.NoteEvent>();
            chordNotes.NoteEvent += OnMidiVoice;

            Explorer.OnBrowserVisibleChange += delegate(object o, bool visible) {
                MainTable.RowStyles[MainTable.GetRow(ChatPlaylistTable)].Height   = visible ? 0 : 100;
                MainTable.RowStyles[MainTable.GetRow(ChatPlaylistTable)].SizeType = visible ? SizeType.Absolute : SizeType.Percent;
                //ChatPlaylistTable.Invoke(t => t.Visible = !visible);

                MainTable.RowStyles[MainTable.GetRow(Explorer)].Height   = visible ? 100 : 30;
                MainTable.RowStyles[MainTable.GetRow(Explorer)].SizeType = visible ? SizeType.Percent : SizeType.Absolute;
            };
            Explorer.OnBrowserSelect += Browser_OnMidiSelect;

            Playlist.OnMidiSelect         += Playlist_OnMidiSelect;
            Playlist.OnPlaylistRequestAdd += Playlist_OnPlaylistRequestAdd;

            if (Properties.Settings.Default.SaveLog)
            {
                FileTarget target = new NLog.Targets.FileTarget("chatlog")
                {
                    FileName          = "logs/ff14log.txt",
                    Layout            = @"${date:format=yyyy-MM-dd HH\:mm\:ss} ${message}",
                    ArchiveDateFormat = "${shortdate}",
                    ArchiveEvery      = FileArchivePeriod.Day,
                    ArchiveFileName   = "logs/ff14log-${shortdate}.txt",
                    Encoding          = Encoding.UTF8,
                };

                var config = new NLog.Config.LoggingConfiguration();
                config.AddRule(LogLevel.Info, LogLevel.Info, target);
                NLog.LogManager.Configuration = config;
            }

            string upath = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming).FilePath;

            //Console.WriteLine(string.Format(".config: [{0}]", upath));

            Settings.RefreshMidiInput();

            Log("Bard Music Player initialized.");
        }
Esempio n. 56
0
        public async Task UpdateNLog(LogLevel MinLevel, string Filename, long MaxSize, int MaxAgeDays, int MaxGUILogItems)
        {
            try
            {
                this.MaxGUILogItems = MaxGUILogItems;

                bool needsupdating = this.NLogFileWriter == null || this.NLogAsyncWrapper == null || MinLevel != this.MinLevel || Filename != this._Filename || MaxSize != this._MaxSize || MaxAgeDays != this._MaxAgeDays;

                if (!needsupdating)
                {
                    return;
                }

                //if we change the logging level only, I dont want to re-initialize everything else...

                bool onlylevel = this.NLogFileWriter != null && this.NLogAsyncWrapper != null && MinLevel != this.MinLevel && Filename == this._Filename && MaxSize == this._MaxSize && MaxAgeDays == this._MaxAgeDays;

                if (onlylevel)
                {
                    this.MinLevel = MinLevel;
                    foreach (var rule in LogManager.Configuration.LoggingRules)
                    {
                        rule.EnableLoggingForLevel(this.MinLevel);
                    }

                    //Call to update existing Loggers created with GetLogger() or
                    //GetCurrentClassLogger()
                    LogManager.ReconfigExistingLoggers();

                    this._Filename = this.GetCurrentLogFileName();

                    return;
                }

                if (this.NLogAsyncWrapper == null)
                {
                    this.NLogAsyncWrapper = new AsyncTargetWrapper();
                }

                this.MinLevel    = MinLevel;
                this._MaxAgeDays = MaxAgeDays;
                this._MaxSize    = MaxSize;

                // Targets where to log to: File and Console
                var    FileTarget = new NLog.Targets.FileTarget("logfile"); // { FileName = AppSettings.Settings.LogFileName };
                string dir        = Path.GetDirectoryName(Filename);
                string justfile   = Path.GetFileNameWithoutExtension(Filename);
                //${basedir}/${shortdate}.log

                FileTarget.FileName = dir + "\\" + justfile + ".[${shortdate}].log";

                FileTarget.ArchiveAboveSize        = MaxSize;
                FileTarget.ArchiveEvery            = NLog.Targets.FileArchivePeriod.Day;
                FileTarget.MaxArchiveDays          = MaxAgeDays;
                FileTarget.ArchiveNumbering        = NLog.Targets.ArchiveNumberingMode.DateAndSequence;
                FileTarget.ArchiveOldFileOnStartup = false;
                FileTarget.ArchiveDateFormat       = "yyyy-MM-dd";
                FileTarget.ArchiveFileName         = dir + "\\" + justfile + ".[{#}].log.zip";


                FileTarget.KeepFileOpen = false;
                FileTarget.CreateDirs   = true;
                FileTarget.Header       = "Date|Level|Source|Func|AIServer|Camera|Image|Detail|Idx|Depth|Color|ThreadID";
                FileTarget.EnableArchiveFileCompression = true;
                FileTarget.Layout = "${message}";  //nothing fancy we are doing it ourselves

                this.NLogAsyncWrapper.WrappedTarget  = FileTarget;
                this.NLogAsyncWrapper.QueueLimit     = 100;
                this.NLogAsyncWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Discard;
                this.NLogAsyncWrapper.Name           = "NLogAsyncWrapper";

                // Rules for mapping loggers to targets
                NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(this.NLogAsyncWrapper, this.MinLevel);
                NLog.LogManager.AutoShutdown = true;

                this.NLogFileWriter = NLog.LogManager.GetCurrentClassLogger();

                //this.NLogAsyncWrapper.EventQueueGrow
                //this.NLogAsyncWrapper.LogEventDropped

                if (this.Values.Count == 0)
                {
                    this.GetCurrentLogFileName();
                }

                //load the current log file into memory
                //await this.LoadLogFileAsync(this._Filename, true, false);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + Global.ExMsg(ex));
            }
        }
Esempio n. 57
0
        public NLogger(LogOptions options = null)
        {
            options = options ?? new LogOptions {
                EnableConsoleLog = true
            };
            var config = new NLog.Config.LoggingConfiguration();

            if (options.EnableFileLog)
            {
                var fileConf = new NLog.Targets.FileTarget("jimuLogFile")
                {
                    FileName         = ".\\log\\${level:lowercase=true}\\${shortdate}.log",
                    ArchiveAboveSize = 10000000,
                    Layout           = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} ${level:uppercase=true}  ${message}"
                };
                if ((options.FileLogLevel & LogLevel.Error) == LogLevel.Error)
                {
                    config.AddRuleForOneLevel(NLog.LogLevel.Error, fileConf);
                }
                if ((options.FileLogLevel & LogLevel.Warn) == LogLevel.Warn)
                {
                    //config.AddRuleForOneLevel(NLog.LogLevel.Warn, fileConf);
                    config.AddRule(NLog.LogLevel.Warn, NLog.LogLevel.Error, fileConf);
                }
                if ((options.FileLogLevel & LogLevel.Info) == LogLevel.Info)
                {
                    config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Error, fileConf);
                    //config.AddRuleForOneLevel(NLog.LogLevel.Info, fileConf);
                }
                if ((options.FileLogLevel & LogLevel.Debug) == LogLevel.Debug)
                {
                    config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Error, fileConf);
                    //config.AddRuleForOneLevel(NLog.LogLevel.Debug, fileConf);
                }
            }

            if (options.EnableConsoleLog)
            {
                var consoleLog = new NLog.Targets.ConsoleTarget("jimuLogconsole")
                {
                    Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} ${level:uppercase=true}  ${message}"
                };
                if ((options.ConsoleLogLevel & LogLevel.Error) == LogLevel.Error)
                {
                    config.AddRuleForOneLevel(NLog.LogLevel.Error, consoleLog);
                }
                if ((options.ConsoleLogLevel & LogLevel.Warn) == LogLevel.Warn)
                {
                    config.AddRule(NLog.LogLevel.Warn, NLog.LogLevel.Error, consoleLog);
                    //config.AddRuleForOneLevel(NLog.LogLevel.Warn, consoleLog);
                }
                if ((options.ConsoleLogLevel & LogLevel.Info) == LogLevel.Info)
                {
                    config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Error, consoleLog);
                    //config.AddRuleForOneLevel(NLog.LogLevel.Info, consoleLog);
                }
                if ((options.ConsoleLogLevel & LogLevel.Debug) == LogLevel.Debug)
                {
                    config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Error, consoleLog);
                    //config.AddRuleForOneLevel(NLog.LogLevel.Debug, consoleLog);
                }
            }
            NLog.LogManager.Configuration = config;
            _logger = NLog.LogManager.GetLogger("jimuLogger");
        }
Esempio n. 58
0
        public Logger(bool isClassLogger = true)
        {
            var appName = Environment.GetEnvironmentVariable("AppName");

#if !UNITY_5_3_OR_NEWER
            var    config    = new NLog.Config.LoggingConfiguration();
            string logFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../logs");
            if (!Directory.Exists(logFolder))
            {
                Directory.CreateDirectory(logFolder);
            }
            string logFilePath = Path.Combine(logFolder, appName + ".log");
            Console.WriteLine("CreateLogFile: " + logFilePath);
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName         = logFilePath,
                Layout           = new NLog.Layouts.SimpleLayout("${longdate} [${level:uppercase=true}] [${threadid}] ${callsite} - ${message}"),
                ArchiveFileName  = "${basedir}/logs/archived/" + appName + ".{#####}.log",
                ArchiveAboveSize = 100000000 /* 100 MB */,
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
                ConcurrentWrites = true,
                KeepFileOpen     = false,
                MaxArchiveFiles  = 10,
            };

            if (!isClassLogger)
            {
                logfile.Layout = new NLog.Layouts.SimpleLayout("${longdate} [${level:uppercase=true}] [${threadid}] ${logger} - ${message}");
            }

            var logconsole = new NLog.Targets.ColoredConsoleTarget("logconsole");

            AsyncTargetWrapper wrapper = new AsyncTargetWrapper();
            wrapper.WrappedTarget  = logfile;
            wrapper.QueueLimit     = 5000;
            wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Grow;

            AsyncTargetWrapper wrapper2 = new AsyncTargetWrapper();
            wrapper2.WrappedTarget  = logconsole;
            wrapper2.QueueLimit     = 5000;
            wrapper2.OverflowAction = AsyncTargetWrapperOverflowAction.Grow;


            config.AddTarget("asyncFile", wrapper);
            config.AddTarget("asyncConsole", wrapper2);

            config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, wrapper2);
            config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, wrapper);
            NLog.LogManager.Configuration = config;
            if (isClassLogger)
            {
                NLogger = NLog.LogManager.GetCurrentClassLogger();
            }
            else
            {
                NLogger = NLog.LogManager.GetLogger(appName);
            }
#else
            string logFolder = Path.Combine(Unity.Common.IOUtil.persistentDataPath, "logs");
            if (!Directory.Exists(logFolder))
            {
                Directory.CreateDirectory(logFolder);
            }
            string logFilePath = Path.Combine(logFolder, appName + ".log");
            Console.WriteLine("CreateLogFile: " + logFilePath);
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName         = logFilePath,
                Layout           = new NLog.Layouts.SimpleLayout("${longdate} [${level:uppercase=true}] [${threadid}] ${callsite} - ${message}"),
                ArchiveFileName  = "${basedir}/logs/archived/" + appName + ".{#####}.log",
                ArchiveAboveSize = 100000000 /* 100 MB */,
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
                ConcurrentWrites = true,
                KeepFileOpen     = false,
                MaxArchiveFiles  = 10,
            };

            if (!isClassLogger)
            {
                logfile.Layout = new NLog.Layouts.SimpleLayout("${longdate} [${level:uppercase=true}] [${threadid}] ${logger} - ${message}");
            }

            AsyncTargetWrapper wrapper = new AsyncTargetWrapper();
            wrapper.WrappedTarget  = logfile;
            wrapper.QueueLimit     = 5000;
            wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Grow;

            AsyncTargetWrapper wrapperUnity = new AsyncTargetWrapper();
            if (isClassLogger)
            {
                wrapperUnity.WrappedTarget = Unity.Common.LogUtil.CreateUnityConsoleTarget("unityconsole", "${longdate} [${level:uppercase=true}] [${threadid}] ${callsite} - ${message}");
            }
            else
            {
                wrapperUnity.WrappedTarget = Unity.Common.LogUtil.CreateUnityConsoleTarget("unityconsole", "${longdate} [${level:uppercase=true}] [${threadid}] ${logger} - ${message}");
            }
            wrapperUnity.QueueLimit     = 5000;
            wrapperUnity.OverflowAction = AsyncTargetWrapperOverflowAction.Grow;

            if (isClassLogger)
            {
                NLogger = Unity.Common.LogUtil.GetLogger(null, (cfg) =>
                {
                    cfg.AddTarget("asyncFile", wrapper);
                    cfg.AddTarget("asyncConsole", wrapperUnity);

                    cfg.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, wrapperUnity);
                    cfg.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, wrapper);
                });
            }
            else
            {
                NLogger = Unity.Common.LogUtil.GetLogger(appName, (cfg) =>
                {
                    cfg.AddTarget("asyncFile", wrapper);
                    cfg.AddTarget("asyncConsole", wrapperUnity);

                    cfg.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, wrapperUnity);
                    cfg.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, wrapper);
                });
            }
#endif
        }
Esempio n. 59
0
        public BmpMain()
        {
            InitializeComponent();

            this.UpdatePerformance();

            BmpUpdate update = new BmpUpdate();

            if (!Program.programOptions.DisableUpdate)
            {
                updateResult = update.ShowDialog();
                if (updateResult == DialogResult.Yes)
                {
                    updateTitle  = update.version.updateTitle;
                    updateText   = update.version.updateText;
                    updateResult = DialogResult.Yes;
                }
                if (updateResult == DialogResult.Ignore)
                {
                    string log = " This is a preview of a future version of BMP! Please be kind and report any bugs or unexpected behaviors to discord channel.";
                    ChatLogAll.AppendRtf(BmpChatParser.FormatRtf(log, Color.LightYellow, true));
                }
                if (!string.IsNullOrEmpty(update.version.updateLog))
                {
                    string log = string.Format("= BMP Update =\n {0} \n", update.version.updateLog);
                    ChatLogAll.AppendRtf(BmpChatParser.FormatRtf(log, Color.LightGreen, true));
                }
            }
            this.Text = update.version.ToString();

            // Clear local orchestra
            InfoTabs.TabPages.Remove(localOrchestraTab);

            LocalOrchestra.onMemoryCheck += delegate(Object o, bool status) {
                if (status)
                {
                    this.FFXIV.memory.StopThread();
                }
                else
                {
                    this.FFXIV.memory.StartThread();
                }
            };

            FFXIV.findProcessRequest += delegate(Object o, EventArgs empty) {
                this.Invoke(t => t.FindProcess());
            };

            FFXIV.findProcessError += delegate(Object o, BmpHook.ProcessError error) {
                this.Invoke(t => t.ErrorProcess(error));
            };

            FFXIV.hotkeys.OnFileLoad += delegate(Object o, EventArgs empty) {
                this.Invoke(t => t.Hotkeys_OnFileLoad(FFXIV.hotkeys));
            };
            FFXIV.hook.OnKeyPressed     += Hook_OnKeyPressed;
            FFXIV.memory.OnProcessReady += delegate(object o, Process proc) {
                this.Log(string.Format("[{0}] Process scanned and ready.", proc.Id));
                if (Sharlayan.Reader.CanGetActors())
                {
                    if (!Sharlayan.Reader.CanGetCharacterId())
                    {
                        this.Log("[MEMORY] Cannot get Character ID.\n Key bindings won't be loaded, load it manually by selecting an ID in the bottom right.");
                    }
                    if (!Sharlayan.Reader.CanGetChatInput())
                    {
                        this.Log("[MEMORY] Cannot get chat input status.\n Automatic pausing when chatting won't work.");
                    }
                    if (!Sharlayan.Reader.CanGetPerformance())
                    {
                        this.Log("[MEMORY] Cannot get performance status.\n Performance detection will not work. Force it to work by ticking Settings > Force playback.");
                    }
                }
                else
                {
                    List <Sharlayan.Models.Signature> signatures = Sharlayan.Signatures.Resolve().ToList();
                    int sigCount = signatures.Count;
                    foreach (Sharlayan.Models.Signature sig in signatures)
                    {
                        if (Sharlayan.Scanner.Instance.Locations.ContainsKey(sig.Key))
                        {
                            sigCount--;
                        }
                        else
                        {
                            Console.WriteLine(string.Format("Could not find signature {0}", sig.Key));
                        }
                    }
                    if (sigCount == signatures.Count)
                    {
                        this.Log(string.Format("[MEMORY] Cannot read memory ({0}/{1}). Functionality will be severely limited.", sigCount, signatures.Count));
                        this.Invoke(t => t.ErrorProcess(BmpHook.ProcessError.ProcessNonAccessible));
                    }
                    else
                    {
                        this.Log("[MEMORY] Cannot read actors. Local performance will be broken.");
                    }
                }
            };
            FFXIV.memory.OnProcessLost += delegate(object o, EventArgs arg) {
                this.Log("Attached process exited.");
            };
            FFXIV.memory.OnChatReceived += delegate(object o, ChatLogItem item) {
                this.Invoke(t => t.Memory_OnChatReceived(item));
            };
            FFXIV.memory.OnPerformanceChanged += delegate(object o, List <uint> ids) {
                this.Invoke(t => t.LocalOrchestraUpdate((o as FFXIVMemory).GetActorItems(ids)));
            };
            FFXIV.memory.OnPerformanceReadyChanged += delegate(object o, bool performance) {
                this.Invoke(t => t.Memory_OnPerformanceReadyChanged(performance));
            };
            FFXIV.memory.OnCurrentPlayerJobChange += delegate(object o, CurrentPlayerResult res) {
                this.Invoke(t => t.Memory_OnCurrentPlayerJobChange(res));
            };
            FFXIV.memory.OnCurrentPlayerLogin += delegate(object o, CurrentPlayerResult res) {
                string world = string.Empty;
                if (Sharlayan.Reader.CanGetWorld())
                {
                    world = Sharlayan.Reader.GetWorld();
                }
                if (string.IsNullOrEmpty(world))
                {
                    this.Log(string.Format("Character [{0}] logged in.", res.CurrentPlayer.Name));
                }
                else
                {
                    this.Log(string.Format("Character [{0}] logged in at [{1}].", res.CurrentPlayer.Name, world));
                }

                if (!Program.programOptions.DisableUpdate)
                {
                    BmpDonationChecker don = new BmpDonationChecker(res.CurrentPlayer.Name, world);
                    don.OnDonatorResponse += delegate(Object obj, BmpDonationChecker.DonatorResponse donres) {
                        if (donres.donator)
                        {
                            if (!string.IsNullOrEmpty(donres.donationMessage))
                            {
                                this.Log(donres.donationMessage);
                            }
                        }
                        this.Invoke(t => t.DonationStatus = donres.donator);
                    };
                }

                this.Invoke(t => t.UpdatePerformance());
            };
            FFXIV.memory.OnCurrentPlayerLogout += delegate(object o, CurrentPlayerResult res) {
                string format = string.Format("Character [{0}] logged out.", res.CurrentPlayer.Name);
                this.Log(format);
            };
            FFXIV.memory.OnPartyChanged += delegate(object o, PartyResult res) {
                this.Invoke(t => t.LocalOrchestraUpdate());
            };

            Player.OnStatusChange += delegate(object o, PlayerStatus status) {
                this.Invoke(t => t.UpdatePerformance());
            };

            Player.OnSongSkip += OnSongSkip;

            Player.OnMidiProgressChange += OnPlayProgressChange;

            Player.OnMidiStatusChange += OnPlayStatusChange;
            Player.OnMidiStatusEnded  += OnPlayStatusEnded;

            Player.OnMidiNote  += OnMidiVoice;
            Player.OffMidiNote += OffMidiVoice;

            Player.Player.OpenInputDevice(Settings.GetMidiInput().name);

            Settings.OnMidiInputChange += delegate(object o, MidiInput input) {
                Player.Player.CloseInputDevice();
                if (input.id != -1)
                {
                    Player.Player.OpenInputDevice(input.name);
                    Log(string.Format("Switched to {0} ({1})", input.name, input.id));
                }
            };
            Settings.OnKeyboardTest += delegate(object o, EventArgs arg) {
                foreach (FFXIVKeybindDat.Keybind keybind in FFXIV.hotkeys.GetPerformanceKeybinds())
                {
                    FFXIV.hook.SendSyncKeybind(keybind);
                    Thread.Sleep(100);
                }
            };

            Settings.OnForcedOpen += delegate(object o, bool open)
            {
                this.Invoke(t => {
                    if (open)
                    {
                        Log(string.Format("Forced playback was enabled. You will not be able to use keybinds, such as spacebar."));
                        WarningLog("Forced playback enabled.");
                    }

                    t.UpdatePerformance();
                });
            };

            Explorer.OnBrowserVisibleChange += delegate(object o, bool visible) {
                MainTable.SuspendLayout();
                MainTable.RowStyles[MainTable.GetRow(ChatPlaylistTable)].Height   = visible ? 0 : 100;
                MainTable.RowStyles[MainTable.GetRow(ChatPlaylistTable)].SizeType = visible ? SizeType.Absolute : SizeType.Percent;
                //ChatPlaylistTable.Invoke(t => t.Visible = !visible);

                MainTable.RowStyles[MainTable.GetRow(Explorer)].Height   = visible ? 100 : 30;
                MainTable.RowStyles[MainTable.GetRow(Explorer)].SizeType = visible ? SizeType.Percent : SizeType.Absolute;
                MainTable.ResumeLayout(true);
            };
            Explorer.OnBrowserSelect += Browser_OnMidiSelect;

            Playlist.OnMidiSelect               += Playlist_OnMidiSelect;
            Playlist.OnPlaylistRequestAdd       += Playlist_OnPlaylistRequestAdd;
            Playlist.OnPlaylistManualRequestAdd += Playlist_OnPlaylistManualRequestAdd;

            this.ResizeBegin += (s, e) => {
                LocalOrchestra.SuspendLayout();
            };
            this.ResizeEnd += (s, e) => {
                LocalOrchestra.ResumeLayout(true);
            };

            if (Properties.Settings.Default.SaveLog)
            {
                FileTarget target = new NLog.Targets.FileTarget("chatlog")
                {
                    FileName          = "logs/ff14log.txt",
                    Layout            = @"${date:format=yyyy-MM-dd HH\:mm\:ss} ${message}",
                    ArchiveDateFormat = "${shortdate}",
                    ArchiveEvery      = FileArchivePeriod.Day,
                    ArchiveFileName   = "logs/ff14log-${shortdate}.txt",
                    Encoding          = Encoding.UTF8,
                    KeepFileOpen      = true,
                };

                var config = new NLog.Config.LoggingConfiguration();
                config.AddRule(LogLevel.Info, LogLevel.Info, target);
                NLog.LogManager.Configuration = config;
            }

            string upath = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming).FilePath;

            //Console.WriteLine(string.Format(".config: [{0}]", upath));

            Settings.RefreshMidiInput();

            Log("Bard Music Player initialized.");
        }