示例#1
0
        public static Logger CreateDebugLogger(string name)
        {
            //string LogEntryLayout = "${ date:format=dd.MM.yyyy HH\\:mm\\:ss.fff} thread[${threadid}] ${logger} (${level:uppercase=true}): ${message}. ${exception:format=ToString}",
            string LogEntryLayout = "${ date:format=dd.MM.yyyy HH\\:mm\\:ss.fff}${level:uppercase=true}: ${message}. ${exception:format=ToString}";
            string logFileLayout  = "logs/{0}.DEBUG.${{shortdate}}.log";

            // Create Targets
            FileTarget target = new FileTarget();

            target.Name = name;
            target.ReplaceFileContentsOnEachWrite = false;
            target.FileName = string.Format(logFileLayout, name);
            target.Layout   = LogEntryLayout;

            // Create Rules
            LoggingRule ruleInfo = new LoggingRule("Debug");

            ruleInfo.LoggerNamePattern = "*";
            ruleInfo.SetLoggingLevels(LogLevel.Debug, LogLevel.Fatal);
            ruleInfo.Targets.Add(target);

            // Create Configuration
            LoggingConfiguration config = new LoggingConfiguration();

            config.AddTarget(name, target);
            config.LoggingRules.Add(ruleInfo);

            LogFactory factory = new LogFactory();

            factory.Configuration = config;
            return(factory.GetCurrentClassLogger());
        }
示例#2
0
        public void LogRuleSetLoggingLevels_enables()
        {
            var rule = new LoggingRule();

            rule.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal);
            Assert.Equal(rule.Levels, new[] { LogLevel.Warn, LogLevel.Error, LogLevel.Fatal });
        }
示例#3
0
        public void LogRuleSetLoggingLevels_off()
        {
            var rule = new LoggingRule();

            rule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel);

            rule.SetLoggingLevels(LogLevel.Off, LogLevel.Off);
            Assert.Equal(rule.Levels, new LogLevel[0]);
        }
示例#4
0
        public void LogRuleSetLoggingLevels_disables()
        {
            var rule = new LoggingRule();

            rule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel);

            rule.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal);
            Assert.Equal(rule.Levels, new[] { LogLevel.Warn, LogLevel.Error, LogLevel.Fatal });
        }
示例#5
0
        /// <summary>
        /// Set the NLog logging level to Debug or Info
        /// </summary>
        /// <param name="debug">If true set level to Debug, otherwise set to Info</param>
        public static void SetLogLevel(bool debug)
        {
            LoggingConfiguration config = LogManager.Configuration;

            LoggingRule rule = config.FindRuleByName("LogToFile");

            if (rule != null)
            {
                if (debug)
                {
                    rule.SetLoggingLevels(LogLevel.Debug, LogLevel.Fatal);
                }
                else
                {
                    rule.SetLoggingLevels(LogLevel.Info, LogLevel.Fatal);
                }
                LogManager.ReconfigExistingLoggers();
            }
        }
示例#6
0
        private static Logger CreateLogger(string name)
        {
            string layoutDebug = "${longdate} - ${level:uppercase=true}: ${message}. ${exception:format=ToString}";
            string layoutTrace = "${longdate} - ${level:uppercase=true} - thread[${threadid}] ${callsite}, Line ${callsite-linenumber}: ${message}. ${exception:format=ToString}";

            string filenameDebug = "logs/{0}.${{shortdate}}.log";
            string filenameTrace = "logs/{0}.TRACE.${{shortdate}}.log";

            // Create Targets
            FileTarget targetDebug = new FileTarget();

            targetDebug.Name     = name;
            targetDebug.FileName = string.Format(filenameDebug, name);
            targetDebug.Layout   = layoutDebug;
            targetDebug.ReplaceFileContentsOnEachWrite = false;

            FileTarget targetTrace = new FileTarget();

            targetTrace.Name     = name;
            targetTrace.FileName = string.Format(filenameTrace, name);
            targetTrace.Layout   = layoutTrace;
            targetTrace.ReplaceFileContentsOnEachWrite = false;

            // Create Rules
            LoggingRule ruleDebug = new LoggingRule("Debug");

            ruleDebug.LoggerNamePattern = "*";
            ruleDebug.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal);
            ruleDebug.Targets.Add(targetDebug);

            LoggingRule ruleTrace = new LoggingRule("Trace");

            ruleTrace.LoggerNamePattern = "*";
            ruleTrace.SetLoggingLevels(LogLevel.Trace, LogLevel.Info);
            ruleTrace.Targets.Add(targetTrace);

            // Create Configuration
            LoggingConfiguration config = new LoggingConfiguration();

            config.AddTarget(name, targetDebug);
            config.AddTarget(name, targetTrace);
            config.LoggingRules.Add(ruleDebug);
            config.LoggingRules.Add(ruleTrace);

            LogFactory factory = new LogFactory();

            factory.Configuration = config;
            return(factory.GetCurrentClassLogger());
        }
示例#7
0
        //public static void SetCustomConfig(Target customTarget)
        //{
        //    LogManager.ThrowExceptions = true;
        //    var config = new LoggingConfiguration();

        //    //Targets
        //    logfile = new FileTarget();
        //    logfile.FileName = "Terahelper.log";
        //    logfile.DeleteOldFileOnStartup = true;
        //    logfile.KeepFileOpen = true;
        //    AsyncTargetWrapper asyncWrapperLog = new AsyncTargetWrapper(logfile);
        //    config.AddTarget("logfile", asyncWrapperLog);

        //    config.AddTarget("form", customTarget);

        //    //Rules
        //    var level = LogLevel.Trace;
        //    switch (CoreSettings.Default.LogLevel)
        //    {
        //        case "info":
        //            level = LogLevel.Info;
        //            break;
        //        case "debug":
        //            level = LogLevel.Debug;
        //            break;
        //        case "trace":
        //            level = LogLevel.Trace;
        //            break;
        //    }
        //    fileLoggingRule = new LoggingRule("*", level, asyncWrapperLog);
        //    config.LoggingRules.Add(fileLoggingRule);

        //    formLoggingRule = new LoggingRule("*", LogLevel.Info, customTarget);
        //    config.LoggingRules.Add(formLoggingRule);


        //    LogManager.Configuration = config;
        //}

        public static void ReloadFileLoggingRule()
        {
            var level = LogLevel.Trace;

            switch (CoreSettings.Default.LogLevel)
            {
            case "info":
                level = LogLevel.Info;
                break;

            case "debug":
                level = LogLevel.Debug;
                break;

            case "trace":
                level = LogLevel.Trace;
                break;
            }

            LogManager.Configuration.LoggingRules.Remove(fileLoggingRule);
            fileLoggingRule.SetLoggingLevels(level, LogLevel.Fatal);
            LogManager.Configuration.LoggingRules.Add(fileLoggingRule);
        }
示例#8
0
        public static LoggingConfiguration GetLoggingConfiguration(RuntimeSettings settings, bool fileOnly = false)
        {
            var logFileName = settings.CustomLogFileName ?? "log.txt";
            var logLevel    = settings.TracingEnabled ? NLog.LogLevel.Debug : NLog.LogLevel.Info;

            // Add custom date time format renderer as the default is too long
            ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("simpledatetime", typeof(SimpleDateTimeRenderer));

            var logConfig = new LoggingConfiguration();

            var logFile = new FileTarget();

            logFile.Layout           = "${longdate} ${level} ${message} ${exception:format=ToString}";
            logFile.FileName         = Path.Combine(settings.DataFolder, logFileName);
            logFile.ArchiveFileName  = Path.Combine(settings.DataFolder, logFileName + ".{#####}.txt");
            logFile.ArchiveAboveSize = 500000;
            logFile.MaxArchiveFiles  = 5;
            logFile.KeepFileOpen     = false;
            logFile.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence;
            logConfig.AddTarget("file", logFile);

            var microsoftRule = new LoggingRule();

            microsoftRule.LoggerNamePattern = "Microsoft.*";
            microsoftRule.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal);
            microsoftRule.Final = true;
            microsoftRule.Targets.Add(logFile);

            var microsoftDebugRule = new LoggingRule();

            microsoftDebugRule.LoggerNamePattern = "Microsoft.*";
            microsoftDebugRule.SetLoggingLevels(LogLevel.Debug, LogLevel.Info);
            microsoftDebugRule.Final = true;
            if (settings.TracingEnabled)
            {
                microsoftDebugRule.Targets.Add(logFile);
            }
            logConfig.LoggingRules.Add(microsoftDebugRule);

            var logFileRule = new LoggingRule("*", logLevel, logFile);

            logConfig.LoggingRules.Add(logFileRule);

            if (!fileOnly)
            {
                var logConsole = new ColoredConsoleTarget();
                logConsole.Layout = "${simpledatetime} ${level} ${message} ${exception:format=ToString}";
                logConfig.AddTarget("console", logConsole);

                var logConsoleRule = new LoggingRule("*", logLevel, logConsole);
                logConfig.LoggingRules.Add(logConsoleRule);

                var logService = new LogCacheService();
                logConfig.AddTarget("service", logService);

                var serviceRule = new LoggingRule("*", logLevel, logService);
                logConfig.LoggingRules.Add(serviceRule);

                microsoftRule.Targets.Add(logConsole);
                microsoftRule.Targets.Add(logService);

                if (settings.TracingEnabled)
                {
                    microsoftDebugRule.Targets.Add(logConsole);
                    microsoftDebugRule.Targets.Add(logService);
                }
            }

            logConfig.LoggingRules.Add(microsoftRule);

            return(logConfig);
        }
示例#9
0
        /// <summary>
        /// Create Custom Logger using parameters passed.
        /// </summary>
        /// <param name="name">Name of file.</param>
        /// <param name="LogEntryLayout">Give "" if you want just message. If omited will switch to full log paramaters.</param>
        /// <param name="logFileLayout">Filename only. No extension or file paths accepted.</param>
        /// <param name="absoluteFilePath">If you want to save the log file to different path thatn application default log path, specify the path here.</param>
        /// <returns>New instance of NLog logger completly isolated from default instance if any</returns>
        public static Logger CreateCustomLogger(string name = "CustomLog",
                                                //string LogEntryLayout = "${date:format=dd.MM.yyyy HH\\:mm\\:ss.fff} thread[${threadid}] ${logger} (${level:uppercase=true}): ${message}. ${exception:format=ToString}",
                                                string LogEntryLayout   = "${longdate} ${level:uppercase=true}: ${message}. ${exception:format=ToString}",
                                                string logFileLayout    = "logs/{0}.${{shortdate}}.log",
                                                string absoluteFilePath = "")
        {
            //var target = new FileTarget();
            //target.Name = name;
            //target.ReplaceFileContentsOnEachWrite = false;
            //if (absoluteFilePath == "")
            //    target.FileName = string.Format(logFileLayout, name);
            //else
            //    target.FileName = string.Format(absoluteFilePath + "//" + logFileLayout, name);
            //if (LogEntryLayout == "") //if user specifes "" then use default layout.
            //    target.Layout = "${message}. ${exception:format=ToString}";
            //else
            //    target.Layout = LogEntryLayout;

            //var config = new LoggingConfiguration();
            //config.AddTarget(name, target);

            //var ruleInfo = new LoggingRule("All");
            //ruleInfo.LoggerNamePattern = "*";
            //ruleInfo.SetLoggingLevels(LogLevel.Trace, LogLevel.Fatal);
            //ruleInfo.Targets.Add(target);

            //config.LoggingRules.Add(ruleInfo);

            //var factory = new LogFactory();
            //factory.Configuration = config;
            //return factory.GetCurrentClassLogger();

            var factory = new LogFactory();
            var target  = new FileTarget();

            target.Name = name;
            if (absoluteFilePath == "")
            {
                target.FileName = string.Format(logFileLayout, name);
            }
            else
            {
                target.FileName = string.Format(absoluteFilePath + "//" + logFileLayout, name);
            }
            if (LogEntryLayout == "") //if user specifes "" then use default layout.
            {
                target.Layout = "${message}. ${exception:format=ToString}";
            }
            else
            {
                target.Layout = LogEntryLayout;
            }
            //var defaultconfig = LogManager.Configuration;
            var config = new LoggingConfiguration();

            config.AddTarget(name, target);

            //var ruleInfo = new LoggingRule("*", NLog.LogLevel.Trace, target);
            var ruleInfo = new LoggingRule("All");

            ruleInfo.LoggerNamePattern = "*";
            ruleInfo.SetLoggingLevels(LogLevel.Trace, LogLevel.Fatal);
            ruleInfo.Targets.Add(target);

            config.LoggingRules.Add(ruleInfo);

            factory.Configuration = config;

            return(factory.GetCurrentClassLogger());
        }
示例#10
0
        private static void Main(string[] args)
        {
            System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
            customCulture.NumberFormat.NumberDecimalSeparator = ".";

            System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
            Parser.Default
            .ParseArguments <KanimToScmlOptions, ScmlToKanimOptions, GenericOptions, DumpOptions, BatchConvertOptions
                             >(args)
            .WithParsed <KanimToScmlOptions>(o => Convert(
                                                 "kanim",
                                                 "scml",
                                                 o.Files.ToList(),
                                                 o))
            .WithParsed <DumpOptions>(o =>
            {
                SetVerbosity(o);

                var files = new List <string>(o.Files);
                var png   = files.Find(path => path.EndsWith(".png"));
                var build = files.Find(path => path.EndsWith("build.bytes"));
                var anim  = files.Find(path => path.EndsWith("anim.bytes"));
                Directory.CreateDirectory(o.OutputPath);
                Utilities.Dump =
                    new StreamWriter(new FileStream(Path.Join(o.OutputPath, "dump.log"), FileMode.Create));
                var reader = new KanimReader(
                    new FileStream(build, FileMode.Open),
                    new FileStream(anim, FileMode.Open),
                    new FileStream(png, FileMode.Open));
                reader.Read();
                Utilities.Dump.Flush();
            })
            .WithParsed <ScmlToKanimOptions>(o => Convert(
                                                 "scml",
                                                 "kanim",
                                                 o.ScmlFile == null ? new List <string>() : new List <string> {
                o.ScmlFile
            },
                                                 o))
            .WithParsed <GenericOptions>(o => Convert(o.InputFormat, o.OutputFormat, o.Files.ToList(), o))
            .WithParsed <BatchConvertOptions>(o =>
            {
                // Silence Info output from kanimal
                var config = new LoggingConfiguration();
                var target = new ConsoleTarget("logconsole")
                {
                    Layout = "[${level}] ${message}"
                };
                var loggingRule1 = new LoggingRule("kanimal_cli.*", target);
                loggingRule1.SetLoggingLevels(LogLevel.Info, LogLevel.Fatal);
                config.LoggingRules.Add(loggingRule1);
                var loggingRule2 = new LoggingRule("kanimal.*", target);
                loggingRule2.SetLoggingLevels(LogLevel.Warn, LogLevel.Fatal);
                config.LoggingRules.Add(loggingRule2);
                LogManager.Configuration = config;

                if (!Directory.Exists(Path.Join(o.AssetDirectory, "Texture2D")))
                {
                    Logger.Fatal($"The path \"{o.AssetDirectory}/Texture2D\" does not exist.");
                    Environment.Exit((int)ExitCodes.IncorrectArguments);
                }

                if (!Directory.Exists(Path.Join(o.AssetDirectory, "TextAsset")))
                {
                    Logger.Fatal($"The path \"{o.AssetDirectory}/TextAsset\" does not exist.");
                    Environment.Exit((int)ExitCodes.IncorrectArguments);
                }

                foreach (var filepath in Directory.GetFiles(Path.Join(o.AssetDirectory, "Texture2D"), "*.png"))
                {
                    var filename = Path.GetFileName(filepath);
                    var basename = Utilities.GetSpriteBaseName(filename);
                    if (basename == "")
                    {
                        Logger.Warn($"Skipping \"{filename}\" as it does not seem to be a valid anim.");
                        continue;
                    }

                    var png = new FileStream(filepath, FileMode.Open);

                    var animPath  = Path.Join(o.AssetDirectory, "TextAsset", $"{basename}_anim.bytes");
                    var buildPath = Path.Join(o.AssetDirectory, "TextAsset", $"{basename}_build.bytes");
                    if (!File.Exists(animPath))
                    {
                        Logger.Warn(
                            $"Skipping \"{basename}\" because it does not have a corresponding anim.bytes file.");
                        continue;
                    }

                    if (!File.Exists(buildPath))
                    {
                        Logger.Warn(
                            $"Skipping \"{basename}\" because it does not have a corresponding build.bytes file.");
                        continue;
                    }

                    var anim  = new FileStream(animPath, FileMode.Open);
                    var build = new FileStream(buildPath, FileMode.Open);

                    var reader = new KanimReader(build, anim, png);
                    try
                    {
                        reader.Read();
                        var writer = new ScmlWriter(reader);
                        writer.SaveToDir(Path.Join(o.OutputPath, reader.BuildData.Name));
                    }
                    catch (Exception e)
                    {
                        Logger.Error($"The following error occured while exporting \"{reader.BuildData.Name}\":");
                        Logger.Error(e.ToString());
                        Logger.Error("Skipping.");
                        continue;
                    }

                    Logger.Info($"Exported \"{reader.BuildData.Name}\".");
                }
            });
        }