Beispiel #1
0
        public void SimpleLogTest()
        {
            var logioTarget = new LogIOTarget();

            logioTarget.Node   = "${machinename}";
            logioTarget.Stream = "${logger}";
            logioTarget.Layout = "Logger: ${logger}  TID: ${threadid} Message: ${message}";

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

            rule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal);

            var config = new LoggingConfiguration();

            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;

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

            logger.Trace("Hello log.io with trace!");
            logger.Debug("Hello log.io with debug!");
            logger.Info("Hello log.io with info!");
            logger.Warn("Hello log.io with warn!");
            logger.Error("Hello log.io with error!");
            logger.Fatal("Hello log.io with fatal!");

            LogManager.Flush();
        }
Beispiel #2
0
        public void LogRuleDisableLoggingLevels()
        {
            var rule = new LoggingRule();

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

            rule.DisableLoggingForLevels(LogLevel.Warn, LogLevel.Fatal);
            Assert.Equal(rule.Levels, new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info });
        }
Beispiel #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]);
        }
Beispiel #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 });
        }
        private void EnableLoggingTarget(out MemoryTarget target, out LoggingRule loggingRule)
        {
            target = new MemoryTarget
            {
                Layout = "${longdate} ${level:uppercase=true:padding=-7} ${message} ${exception:format=tostring}"
            };

            loggingRule = new LoggingRule();
            loggingRule.Targets.Add(target);
            loggingRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal);
            LogManager.Configuration.LoggingRules.Add(loggingRule);
            LogManager.ReconfigExistingLoggers();
        }
Beispiel #6
0
        public void SetLogLevels(string MinLevel, string MaxLevel = "")
        {
            if (!Initialized)
            {
                throw new InvalidOperationException("Not initialized.");
            }

            try {
                var min = LogLevel.FromString(MinLevel);
                var max = LogLevel.FromString(MaxLevel != String.Empty ? MaxLevel : MinLevel);

                rule.DisableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal);
                rule.EnableLoggingForLevels(min, max);
                LogManager.ReconfigExistingLoggers();
            }
            catch (Exception ex) {
                ilogger.Error(ex, "Internal error");
                throw new InvalidOperationException(ex.Message);
            }
        }
        public FileLoggingConfigurator(string targetName, string[] namePatterns, string defaultFilePath)
        {
            _target = new FileTarget
            {
                Name = targetName,
            };

            _target.FileName = defaultFilePath;

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

                rule.Targets.Add(_target);
                rule.Targets.Add(TorchUtils.GetWpfTarget());
                rule.EnableLoggingForLevels(LogLevel.Info, LogLevel.Off);
                _rules[i] = rule;
            }
        }
Beispiel #8
0
        public void SanizeNewLines()
        {
            var logioTarget = new LogIOTarget();

            logioTarget.Node   = "${machinename}";
            logioTarget.Stream = "${logger}";
            logioTarget.Layout = "Logger: ${logger}  TID: ${threadid} Message: ${message}";

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

            rule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal);

            var config = new LoggingConfiguration();

            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;

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

            logger.Info("Hello\r\nlog.io\r\nwith\r\nnewline!");

            LogManager.Flush();
        }
Beispiel #9
0
        public void ConfigureLogging()
        {
            // Intialize Config Object
            LoggingConfiguration config = new LoggingConfiguration();

            // Initialize Console Target
            var consoleTarget = new ColoredConsoleTarget("Console Target")
            {
                Layout = @"${time} ${longdate} ${uppercase: ${level}} ${logger} ${message} ${exception: format=ToString}"
            };

            // Initialize the AsyncWrapper for the ConsoleTarget
            AsyncTargetWrapper consoleWrapper = new AsyncTargetWrapper();

            consoleWrapper.WrappedTarget  = consoleTarget;
            consoleWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block;
            consoleWrapper.QueueLimit     = 5000;

            // Initialize the AsyncFlushTargetWrapper for the ConsoleWrapper
            AutoFlushTargetWrapper consoleFlushWrapper = new AutoFlushTargetWrapper();

            consoleFlushWrapper.WrappedTarget = consoleWrapper;

            // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule
            consoleFlushWrapper.Condition = "level >= LogLevel.Trace";

            // Adding the target to the config
            config.AddTarget("console", consoleFlushWrapper);


            // Initialize File Target
            var fileTarget = new FileTarget("File Target")
            {
                FileName     = "Logs\\${cached:cached=true:Inner=${date:format=dd.MM.yyyy HH-mm}:CacheKey=${shortdate}}.log",
                KeepFileOpen = false,
                Layout       = @"[${date:format=dd.MM.yyyy HH-mm-ss}] ${message} ${exception: format=ToString}"
            };

            // Initialize the AsyncWrapper for the fileTarget
            AsyncTargetWrapper fileWrapper = new AsyncTargetWrapper();

            fileWrapper.WrappedTarget  = fileTarget;
            fileWrapper.QueueLimit     = 5000;
            fileWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block;

            // Initialize the AsyncFlushTargetWrapper for the FileWrapper
            AutoFlushTargetWrapper fileFlushWrapper = new AutoFlushTargetWrapper();

            fileFlushWrapper.WrappedTarget = fileWrapper;

            // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule
            fileFlushWrapper.Condition = "level >= LogLevel.Trace";

            // Adding the target to the config
            config.AddTarget("file", fileFlushWrapper);

            // Creating the Log Level rules for each target and adding them to the config
            // Edit these to change what methods are logged
            var fileRule = new LoggingRule("*", fileTarget);

            fileRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Info);
            fileRule.EnableLoggingForLevel(LogLevel.Error);
            config.LoggingRules.Add(fileRule);

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

            consoleRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Info);
            consoleRule.EnableLoggingForLevel(LogLevel.Error);
            config.LoggingRules.Add(consoleRule);

            // Assigning the configuration to the logger
            LogManager.Configuration = config;
        }
Beispiel #10
0
        //class TestLogManager
        //{
        //    // A Logger dispenser for the current configuration (Remember to call Flush on application exit)
        //    public static LogFactory Instance { get { return instance.Value; } }
        //    private static Lazy<LogFactory> instance = new Lazy<LogFactory>(BuildLogFactory);


        //    private static LogFactory BuildLogFactory()
        //    {
        //        // Initialize LogFactory object
        //        LogFactory logFactory = new LogFactory();

        //        // Initialize LogFactory Configuration
        //        LoggingConfiguration config = new LoggingConfiguration();


        //        // Register the custom layout to show stack trace in logs
        //        LayoutRenderer.Register("IndentationLayout", typeof(IndentationLayoutRenderer)); //no space

        //        // Initialize File Target
        //        var fileTarget = new FileTarget("File Target")
        //        {
        //            FileName = "${basedir}/logs/logTest.xml",
        //            DeleteOldFileOnStartup = true, // Deletes old log file every time log is called. Set to true simply for testing purposes
        //            KeepFileOpen = true, // Keeps file open regardless of logger status. (Increases performance)
        //            OpenFileCacheTimeout = 30, // Max number of seconds file is kept open. (Increases performance, but the value will scale with the scope of logger implementation)
        //            Layout = "${IndentationLayout} ${longdate} | ${level:uppercase=true} | ${logger} | ${message} | ${callsite:className=true:fileName=false:includeSourcePath=false:methodName=true}" //use IndentationLayout
        //        };


        //        // Initialize the AsyncWrapper for the fileTarget
        //        AsyncTargetWrapper fileWrapper = new AsyncTargetWrapper();
        //        fileWrapper.WrappedTarget = fileTarget;
        //        fileWrapper.QueueLimit = 5000;  // Limits number of requests in the request queue (Improves performance)
        //        fileWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block; // Blocks incoming requests until request queue if has space

        //        // Initialize the AsyncFlushTargetWrapper for the FileWrapper
        //        AutoFlushTargetWrapper fileFlushWrapper = new AutoFlushTargetWrapper();
        //        fileFlushWrapper.WrappedTarget = fileWrapper;

        //        // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule
        //        fileFlushWrapper.Condition = "level >= LogLevel.Info";

        //        // Adding the target to the config
        //        config.AddTarget("file", fileFlushWrapper);

        //        // Creating the Log Level rules for each target and adding them to the config
        //        var fileRule = new LoggingRule("*", fileTarget);
        //        fileRule.EnableLoggingForLevel(exceptionLevel);
        //        fileRule.EnableLoggingForLevels(minLevel, maxLevel);
        //        config.LoggingRules.Add(fileRule);

        //        // Assigning the configuration to the logger
        //        logFactory.Configuration = config;

        //        return logFactory;
        //    }
        //}
        private void SetupLoggingConfiguration()
        {
            // Intialize Config Object
            LoggingConfiguration config = new LoggingConfiguration();

            LayoutRenderer.Register("IndentationLayout", typeof(IndentationLayoutRenderer)); //no space

            /*
             * // Initialize Console Target
             * var consoleTarget = new ColoredConsoleTarget("Console Target")
             * {
             * Layout = @"${time} ${longdate} ${uppercase: ${level}} ${logger} ${message} ${exception: format=ToString}"
             * };
             *
             * // Initialize the AsyncWrapper for the ConsoleTarget
             * AsyncTargetWrapper consoleWrapper = new AsyncTargetWrapper();
             * consoleWrapper.WrappedTarget = consoleTarget;
             * consoleWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block;
             * consoleWrapper.QueueLimit = 5000;
             *
             * // Initialize the AsyncFlushTargetWrapper for the ConsoleWrapper
             * AutoFlushTargetWrapper consoleFlushWrapper = new AutoFlushTargetWrapper();
             * consoleFlushWrapper.WrappedTarget = consoleWrapper;
             *
             * // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule
             * consoleFlushWrapper.Condition = "level >= LogLevel.Info";
             *
             * // Adding the target to the config
             * config.AddTarget("console", consoleFlushWrapper);
             */


            // Initialize File Target
            var fileTarget = new FileTarget("File Target")
            {
                FileName = @"${basedir}\logs\Robotics Automation Log.xml",
                DeleteOldFileOnStartup = true,                                                                               // Deletes old log file every time log is called. Set to true simply for testing purposes
                KeepFileOpen           = true,                                                                               // Keeps file open regardless of logger status. (Increases performance)
                OpenFileCacheTimeout   = 30,                                                                                 // Max number of seconds file is kept open. (Increases performance, but the value will scale with the scope of logger implementation)
                Layout = @"${IndentationLayout} ${date:format=yyyy-MM-dd HH\:mm\:ss} | ${level:uppercase=true} | ${message}" //use IndentationLayout
            };

            //// XmlLayout Configuration
            //var XmlLayout = new XmlLayout();



            //XmlLayout.IndentXml = true;
            //XmlLayout.ElementName = "Automated Test";
            //XmlLayout.ElementValue = "Current Test";  // Unit Test name can be entered into here so each log entry will include Unit Test
            //XmlLayout.MaxRecursionLimit = 10;


            //XmlLayout.Attributes.Add(new XmlAttribute("Time", "${longdate}"));
            //XmlLayout.Attributes.Add(new XmlAttribute("Level", "${level:upperCase=true"));
            //XmlLayout.Elements.Add(new XmlElement("Output", "${message}"));
            //XmlLayout.Elements.Add(new XmlElement("Location", "${callsite:methodName=true}"));

            //fileTarget.Layout = XmlLayout;


            // Initialize the AsyncWrapper for the fileTarget
            AsyncTargetWrapper fileWrapper = new AsyncTargetWrapper();

            fileWrapper.WrappedTarget  = fileTarget;
            fileWrapper.QueueLimit     = 5000;                                   // Limits number of requests in the request queue (Improves performance)
            fileWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block; // Blocks incoming requests until request queue if has space

            // Initialize the AsyncFlushTargetWrapper for the FileWrapper
            AutoFlushTargetWrapper fileFlushWrapper = new AutoFlushTargetWrapper();

            fileFlushWrapper.WrappedTarget = fileWrapper;

            /*
             * // Initiliaze Database Target
             * var dbTarget = new DatabaseTarget
             * {
             *  ConnectionString = WhatINeed,
             *  DBProvider = "MongoServer",
             *  Name = "Mongo",
             *  CommandText =
             *      @"insert into dbo.Log (
             *          Logged, Level, Message, Username, Url, Logger, Callsite, Exception, Stacktrace, remoteAddress
             *      ) values(
             *          @Logged, @Level, @Message, @Username, @Url, @Logger, @Callsite, @Exception, @Stacktrace, @remoteAddress
             *      );"
             * };
             *
             * // Adding all database parameters to pass through Mongo
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Logged", "${date}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Level", "${level}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Username", "${identity}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Url", "${I need this}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Logger", "${logger}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Callsite", "${callsite}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@Exception", "${exception:format=toString}"));
             * dbTarget.Parameters.Add(new DatabaseParameterInfo("@StackTrace", "${stacktrace}"));
             *
             * // Add the target to the config
             * config.AddTarget("database", dbTarget);
             *
             * var databaseRule = new LoggingRule("DatabaseRule", LogLevel.Trace, dbTarget);
             * config.LoggingRules.Add(databaseRule);
             */

            // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule
            fileFlushWrapper.Condition = "level >= LogLevel.Info";

            // Adding the target to the config
            config.AddTarget("file", fileFlushWrapper);

            // Creating the Log Level rules for each target and adding them to the config
            var fileRule = new LoggingRule("*", fileTarget);

            fileRule.EnableLoggingForLevel(exceptionLevel);
            fileRule.EnableLoggingForLevels(minLevel, maxLevel);
            config.LoggingRules.Add(fileRule);

            /*
             * var consoleRule = new LoggingRule("*", consoleTarget);
             * consoleRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Info);
             * consoleRule.EnableLoggingForLevel(LogLevel.Error);
             * config.LoggingRules.Add(consoleRule);
             */

            // Assigning the configuration to the logger
            LogManager.Configuration = config;
        }
Beispiel #11
0
        private static int Main(string[] args)
        {
            LoggingConfiguration config = LogManager.Configuration;

            if (config == null)
            {
                Console.WriteLine("\n~~~~~~~~~~~ Failed to get log configuration ~~~~~~~~~~~\n");
                return(-99);
            }
            LoggingRule fileRule    = config.FindRuleByName("file rule");
            LoggingRule consoleRule = config.FindRuleByName("console rule");

            fileRule.DisableLoggingForLevels(LogLevel.Info, LogLevel.Fatal);
            LogManager.Configuration = config;

            string script;

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            var p = new FluentCommandLineParser <AppArguments>();

            p.Setup(arg => arg.ShowBuildVersion)
            .As('v', "version")
            .Callback(arg =>
            {
                showBuildVersion = arg;
            })
            .SetDefault(false)
            .WithDescription("Show build version");

            p.Setup(arg => arg.ScriptFile)
            .As('s', "script")
            //.Required()
            .WithDescription("Script file.");

            p.Setup(arg => arg.UserName)
            .As('u', "user")
            .WithDescription("Run script against AD Account name.");

            p.Setup(arg => arg.ShowAlert)
            .As('a', "alert")
            .Callback(arg => showUserAlert = arg)
            .SetDefault(false)
            .WithDescription("Notify the user if error. Default: FALSE (Don't notify)");

            p.Setup(arg => arg.HideConsole)
            .As('h', "hide")
            .Callback(arg => hideConsole = arg)
            .SetDefault(false)
            .WithDescription("Hide console window during execution. Default: FALSE (Don't hide console)");

            p.Setup(arg => arg.GetFirstAvailableLetter)
            .As('f', "first")
            .Callback(arg => getFirstAvailableLetter = arg)
            .SetDefault(false)
            .WithDescription("Resolve drive letter conflict to first available. Default: FALSE (Resolve to next available drive letter)");

            p.SetupHelp("?", "help")
            .Callback(text => Console.WriteLine(text));

            var result = p.Parse(args);

            if (showBuildVersion)
            {
                log.Info(version);
                return(0);
            }

            log.Info("");
            log.Info($"Hikari V{version} - created by Stefan Bazelkov");

            if (result.HelpCalled)
            {
                stopwatch.Stop();
                ShowUsage();
                return(0);
            }

            if (result.EmptyArgs)
            {
                p.HelpOption.ShowHelp(p.Options);
                ShowUsage();
                stopwatch.Stop();
                return(0);
            }

            if (result.HasErrors)
            {
                log.Error(result.ErrorText);
                stopwatch.Stop();
                log.Info($"Time elapsed: {stopwatch.Elapsed.TotalSeconds:00.00}s");
                ShowUserAlert("Command line arguments parsing failed!");
                return(-1);
            }

            if (hideConsole)
            {
                // do not show log if console is hidden
                consoleRule.DisableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal);
                ShowWindow(GetConsoleWindow(), ERROR_SW_HIDE);
                log.Info("Start with console window hidden.");
            }

            AppArguments appArg = p.Object;

            if (!File.Exists(appArg.ScriptFile))
            {
                log.Error($"\"{appArg.ScriptFile}\" doesn't exist!");
                stopwatch.Stop();
                log.Info($"Time elapsed: {stopwatch.Elapsed.TotalSeconds:00.00}s");
                ShowUserAlert($"Missing or wrong script file '{appArg.ScriptFile}'!");
                return(-2);
            }

            if (!string.IsNullOrEmpty(appArg.UserName))
            {
                user = ActiveDirectoryHelper.FindPrincipal(appArg.UserName);
                if (user == null)
                {
                    stopwatch.Stop();
                    log.Info($"Time elapsed: {stopwatch.Elapsed.TotalSeconds:00.00}s");
                    log.Error($"Error in resolving provided username: \"{appArg.UserName}\"");
                    return(-6);
                }
            }

            if (user != null)
            {
                // Do not map network drives if username argument is present
                // Only check the network shares to be connected for that AD user
                doMapping = false;
                log.Warn($"Checking mappings for \"{user.SamAccountName}\".");
                log.Warn("No network drives will be connected.");
            }
            else
            {
                // logging will be performed only in the console
                fileRule.EnableLoggingForLevels(LogLevel.Info, LogLevel.Fatal);
                LogManager.Configuration = config;
                doMapping = true;
                user      = UserPrincipal.Current;
                DisconnectAllLocalNetworkDrives();
                log.Info($"Connecting network drives for \"{user.SamAccountName}\".");
            }

            groups = ActiveDirectoryHelper.GetMembership(user).ToList();

            Console.WriteLine();

            log.Info($"Processing \"{appArg.ScriptFile}\" script ...");

            using (StreamReader file = new StreamReader(appArg.ScriptFile))
            {
                script = file.ReadToEnd();
                file.Close();
            }

            var parser = new HikariScriptParser(groups);

            try
            {
                parser.UserName = user.SamAccountName;
                parser.Parse(script);
                log.Info(parser.Model);
            }
            catch (HikariParserException x)
            {
                Console.WriteLine();
                log.Error(x.Message);
                Console.WriteLine();
                log.Warn("No drives will be connected!");
                Console.WriteLine();
                return(-7);
            }

            // Resolve and map the network drives
            ResolveMappings(parser.Model);

            if (doMapping)
            {
                DisconnectAllLocalNetworkDrives();
                ConnectNetworkDrives(parser.Model);
                ConnectNetworkPrinters(parser.Model);
            }

            stopwatch.Stop();
            Console.WriteLine();
            log.Info($"Total time elapsed: {stopwatch.Elapsed.TotalSeconds:00.00}s");
            Console.WriteLine();

            return(0);
        }