Exemplo n.º 1
0
        public void DefaultSmtpClientTest()
        {
            var mailTarget = new MailTarget();
            var client     = mailTarget.CreateSmtpClient();

            Assert.IsInstanceOfType(client, typeof(MySmtpClient));
        }
Exemplo n.º 2
0
        public void MailTarget_UseSystemNetMailSettings_False_ReadFromFromConfigFile()
        {
#if !NETSTANDARD
            var mmt = new MailTarget()
            {
                From       = null,
                To         = "*****@*****.**",
                SmtpServer = "server1",
                SmtpPort   = 27,
                Body       = "${level} ${logger} ${message}",
                UseSystemNetMailSettings = false,
                SmtpSection = new SmtpSection {
                    From = "*****@*****.**"
                }
            };
            Assert.Null(mmt.From);

            Assert.Throws <NLogConfigurationException>(() =>
                                                       new LogFactory().Setup().LoadConfiguration(cfg => {
                cfg.LogFactory.ThrowConfigExceptions = true;
                cfg.Configuration.AddRuleForAllLevels(mmt);
            })
                                                       );
#endif
        }
Exemplo n.º 3
0
        public void DefaultSmtpClientTest()
        {
            var mailTarget = new MailTarget();
            var client     = mailTarget.CreateSmtpClient();

            Assert.IsType(typeof(MySmtpClient), client);
        }
Exemplo n.º 4
0
        public void MailTarget_UseSystemNetMailSettings_True_ReadFromFromConfigFile()
        {
#if !NETSTANDARD
            var mmt = new MailTarget()
            {
                From       = null,
                To         = "*****@*****.**",
                SmtpServer = "server1",
                SmtpPort   = 27,
                Body       = "${level} ${logger} ${message}",
                UseSystemNetMailSettings = true,
                SmtpSection = new SmtpSection {
                    From = "*****@*****.**"
                }
            };
            Assert.Equal("*****@*****.**", mmt.From.ToString());

            new LogFactory().Setup().LoadConfiguration(cfg =>
            {
                cfg.Configuration.AddRuleForAllLevels(mmt);
            });

            Assert.Equal("*****@*****.**", mmt.From.ToString());
#endif
        }
Exemplo n.º 5
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;
        }
Exemplo n.º 6
0
        public void ParseMessagePriorityTests(string input, MessagePriority expected)
        {
            // Act
            var result = MailTarget.ParseMessagePriority(input);

            // Assert
            Assert.Equal(expected, result);
        }
Exemplo n.º 7
0
        private static void Programing()
        {
            FileTarget target = new FileTarget();

            target.Layout   = "${longdate} ${logger} ${message}";
            target.FileName = "${basedir}/KNLogs/${date:format=yyyyMMdd}.log";

            MailTarget mailTarget = new MailTarget();

            mailTarget.Layout      = "${longdate}|${level:uppercase=true}|${logger}|${message}";
            mailTarget.AddNewLines = true;
            mailTarget.To          = "*****@*****.**";
            //mailTarget.From = "*****@*****.**";
            //mailTarget.SmtpAuthentication = SmtpAuthenticationMode.Basic;
            //mailTarget.SmtpPort = 587;
            //mailTarget.SmtpServer = "smtp.gmail.com";
            //mailTarget.SmtpUserName = "******";
            //mailTarget.SmtpPassword = "******";
            //mailTarget.EnableSsl = true;
            var smtpSection = (SmtpSection)System.Configuration.ConfigurationManager.GetSection("system.net/mailSettings/smtp");

            mailTarget.From = smtpSection.From;
            mailTarget.SmtpAuthentication = SmtpAuthenticationMode.Basic;
            mailTarget.SmtpPort           = smtpSection.Network.Port;
            mailTarget.SmtpServer         = smtpSection.Network.Host;
            mailTarget.SmtpUserName       = smtpSection.Network.UserName;
            mailTarget.SmtpPassword       = smtpSection.Network.Password;
            mailTarget.EnableSsl          = smtpSection.Network.EnableSsl;
            mailTarget.Subject            = "${machinename}-${event-properties:item=stage}-${longdate}";
            mailTarget.Body = "[log time]: ${longdate}${newline}[log level]: ${level:uppercase=true}${newline}[log by]: ${logger}${newline}[log message]: ${message}";

            // NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
            // NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(mailTarget, LogLevel.Error);
            LogManager.Configuration = new LoggingConfiguration();
            var fileRule = new LoggingRule("SysCore", LogLevel.Trace, target);

            LogManager.Configuration.AddTarget("file", target);
            LogManager.Configuration.LoggingRules.Add(fileRule);

            var mailRule = new LoggingRule("SysCore", LogLevel.Error, mailTarget);

            LogManager.Configuration.AddTarget("mail", mailTarget);
            LogManager.Configuration.LoggingRules.Add(mailRule);
            LogManager.ReconfigExistingLoggers();//覆寫預設組態
            var log = LogManager.GetLogger("SysCore");

            // log.Error("Kim Trace");

            LogEventInfo myEvent = new LogEventInfo(LogLevel.Error, log.Name, "My debug message");

            myEvent.Properties.Add("stage", "QAS");

            log.Log(myEvent);
        }
Exemplo n.º 8
0
        //:::::::::::::::::::::::::::::::::

        /// <summary>
        ///
        /// </summary>
        /// <param name="inSubject"></param>
        private void setMailLoggerSubject(string inSubject)
        {
            MailTarget target = new MailTarget();

            target.Name               = @"errorGmail";
            target.SmtpServer         = @"smtp.gmail.com";
            target.SmtpPort           = 587;
            target.SmtpAuthentication = NLog.Targets.SmtpAuthenticationMode.Basic;
            target.EnableSsl          = true;

            target.SmtpUserName = @"*****@*****.**";
            target.SmtpPassword = @"1202matemenu";
            //target.SmtpUserName = @"*****@*****.**";
            //target.SmtpPassword = @"matemenu1202";

            target.From = @"*****@*****.**";
            //            target.To = @"*****@*****.**";
            //            target.From = @"*****@*****.**";
            target.To = @"*****@*****.**";

            //target.Subject = string.Format(@"{0}  Version 5.3.0.12", inSubject);
            target.Subject = string.Format(@"{0}  Version __MM_VERSION__", inSubject);
            target.Body    = @"${message}";
            //target.Body = @"${date}: ${message}";

            LoggingConfiguration config = LogManager.Configuration;

            //......................................

            try
            {
                if (config.FindTargetByName(target.Name) != null)
                {
                    config.RemoveTarget(target.Name);
                    config = config.Reload();
                }

                //config.RemoveTarget(target.Name);
            }
            catch (Exception)
            {
            }

            //......................................

            config.AddTarget("errorGmail", target);
            config.LoggingRules.Add(new NLog.Config.LoggingRule("eMail", LogLevel.Error, target));

            //LogManager.Configuration.AddTarget("errorGmail", target);
            //LogManager.Configuration.LoggingRules.Add(new NLog.Config.LoggingRule("eMail", LogLevel.Error, target));

            LogManager.Configuration = config;
        }
Exemplo n.º 9
0
            private MailTarget _getBasicMailTarget()
            {
                var target = new MailTarget();

                target.AddNewLines = true;
                target.Encoding    = Encoding.UTF8;
                target.Layout      = "${longdate}|${level:uppercase=true}|${logger}|${message}${newline}${exception:format=ToString:innerFormat=ToString:maxInnerExceptionLevel=10}";
                target.Html        = true;
                target.ReplaceNewlineWithBrTagInHtml = true;
                target.Subject = "Errors from " + _appName + "@${ark.hostname}";

                return(target);
            }
Exemplo n.º 10
0
        public void MailTarget_UseSystemNetMailSettings_False_ReadFromFromConfigFile()
        {
            var mmt = new MailTarget()
            {
                From       = null,
                To         = "*****@*****.**",
                SmtpServer = "server1",
                SmtpPort   = 27,
                Body       = "${level} ${logger} ${message}",
                UseSystemNetMailSettings = false,
                SmtpSection = new SmtpSection {
                    From = "*****@*****.**"
                }
            };

            Assert.Null(mmt.From);

            Assert.Throws <NLogConfigurationException>(() => mmt.Initialize(null));
        }
Exemplo n.º 11
0
        public static void Configure()
        {
            var config     = NLog.LogManager.Configuration;
            var fileTarget = new FileTarget("fileTarget");
            var mailTarget = new MailTarget("mailTarget");

            config.AddTarget(fileTarget);
            config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Info, fileTarget);
            config.AddTarget(mailTarget);
            config.AddRule(NLog.LogLevel.Warn, NLog.LogLevel.Fatal, mailTarget);

            var prop = new NameValueCollection
            {
                { "configType", "FILE" },
                { "configFile", "~/NLog.config" }
            };

            LogManager.Adapter = new NLogLoggerFactoryAdapter(prop);
        }
        /// <summary>
        /// 動態取得 EMailLog 的 NLog Configuration.
        /// </summary>
        /// <returns></returns>
        public static Logger GetEMailLogConfig(LogLevel logLevel)
        {
            LoggingConfiguration config = new LoggingConfiguration();

            var mailLogTarget = new MailTarget();

            mailLogTarget.Name = "mail";

            mailLogTarget.SmtpServer         = "[yourSmtp]";
            mailLogTarget.SmtpPort           = 25;
            mailLogTarget.SmtpAuthentication = SmtpAuthenticationMode.Basic;
            mailLogTarget.SmtpUserName       = "******";
            mailLogTarget.SmtpPassword       = "******";
            mailLogTarget.EnableSsl          = false;
            mailLogTarget.From        = "[from01] &lt;[from02] &gt;";
            mailLogTarget.To          = "[to]";
            mailLogTarget.Html        = true;
            mailLogTarget.Encoding    = Encoding.UTF8;
            mailLogTarget.AddNewLines = true;
            mailLogTarget.Subject     = "System message for WebHost:${machinename} 於 ${shortdate} ${time} Create ${level} record of level.";
            mailLogTarget.Header      = "=========================================================================";
            mailLogTarget.Body        = @"Time:${longdate}
                ${newline}Log Level:${level:uppercase=true}
                ${newline}Logger:${logger}
                ${newline}Source:${callsite:className=true}
                ${newline}Exception Type:${exception:format=type}
                ${newline}Error Message:${message}
                ${newline}${onexception:${exception:format=tostring}} ${newline}";

            mailLogTarget.Footer = "=========================================================================";

            config.AddTarget("mail", mailLogTarget);

            LoggingRule rule = new LoggingRule("*", logLevel, mailLogTarget);

            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;

            Logger logger = LogManager.GetLogger("NLogHelper");

            return(logger);
        }
Exemplo n.º 13
0
        private static MailTarget CreateNLogConfig(string username = null, string password = null)
        {
            var target = new MailTarget("mail1")
            {
                SmtpAuthentication = SmtpAuthenticationMode.None,
                SmtpServer         = "localhost",
                To           = "*****@*****.**",
                From         = "*****@*****.**",
                SmtpUserName = username,
                SmtpPassword = password
            };

            var loggingConfiguration = new LoggingConfiguration();

            loggingConfiguration.AddRuleForAllLevels(target);

            LogManager.Configuration = loggingConfiguration;

            return(target);
        }
Exemplo n.º 14
0
        public void MailTarget_UseSystemNetMailSettings_True_ReadFromFromConfigFile()
        {
            var mmt = new MailTarget()
            {
                From       = null,
                To         = "*****@*****.**",
                SmtpServer = "server1",
                SmtpPort   = 27,
                Body       = "${level} ${logger} ${message}",
                UseSystemNetMailSettings = true,
                SmtpSection = new SmtpSection {
                    From = "*****@*****.**"
                }
            };

            Assert.Equal("'*****@*****.**'", mmt.From.ToString());

            mmt.Initialize(null);

            Assert.Equal("'*****@*****.**'", mmt.From.ToString());
        }
Exemplo n.º 15
0
    static void Main(string[] args)
    {
        try
        {
            NLog.Internal.InternalLogger.LogToConsole = true;
            NLog.Internal.InternalLogger.LogLevel     = LogLevel.Trace;
            Console.WriteLine("Setting up the target...");
            MailTarget target = new MailTarget();

            target.SmtpServer = "192.168.0.15";
            target.From       = "*****@*****.**";
            target.To         = "*****@*****.**";
            target.Subject    = "sample subject";
            target.Body       = "${message}${newline}";

            BufferingTargetWrapper buffer = new BufferingTargetWrapper(target, 5);

            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(buffer, LogLevel.Debug);

            Console.WriteLine("Sending...");
            Logger logger = LogManager.GetLogger("Example");
            logger.Debug("log message 1");
            logger.Debug("log message 2");
            logger.Debug("log message 3");
            logger.Debug("log message 4");
            logger.Debug("log message 5");
            logger.Debug("log message 6");
            logger.Debug("log message 7");
            logger.Debug("log message 8");

            // this should send 2 mails - one with messages 1..5, the other with messages 6..8
            Console.WriteLine("Sent.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("EX: {0}", ex);
        }
    }
Exemplo n.º 16
0
    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Setting up the target...");
            MailTarget target = new MailTarget();

            target.SmtpServer = "192.168.0.15";
            target.From       = "*****@*****.**";
            target.To         = "*****@*****.**";
            target.Subject    = "sample subject";

            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);

            Console.WriteLine("Sending...");
            Logger logger = LogManager.GetLogger("Example");
            Console.WriteLine("Sent.");
            logger.Debug("log message");
        }
        catch (Exception ex)
        {
            Console.WriteLine("EX: {0}", ex);
        }
    }
Exemplo n.º 17
0
        private MailTarget GetEmailTarget()
        {
            var email = new MailTarget
            {
                SmtpAuthentication = SmtpAuthenticationMode.Basic,


                EnableSsl    = true,
                From         = MZHelperConfiguration.MZemail.MZNormalSend.MZFrom,
                SmtpUserName = MZHelperConfiguration.MZemail.MZNormalSend.MZUserName,
                SmtpPassword = MZHelperConfiguration.MZemail.MZNormalSend.MZPassword,
                SmtpPort     = MZHelperConfiguration.MZemail.MZNormalSend.MZPort,
                SmtpServer   = MZHelperConfiguration.MZemail.MZNormalSend.MZServer,
                Subject      = string.Format(MZConsts.MZLogger.LoggerEmailTargetSubject, _logName, MZHelperConfiguration.MZAppName, MZHelperConfiguration.MZAppUrl),
                To           = MZHelperConfiguration.MZemail.MZDefaultReceiver,
                Layout       = EmailLayout,
                ReplaceNewlineWithBrTagInHtml = true,
                AddNewLines = true,
                Html        = true,
                Name        = MZConsts.MZLogger.LoggerEmailTargetName
            };

            return(email);
        }
Exemplo n.º 18
0
        static Log()
        {
            try
            {
                // Настройка конфигурации логгера.
                _logger = LogManager.GetLogger("AutoCAD_PIK_Manager");
                string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var    config         = new LoggingConfiguration();

                // Локальный лог
                var fileLocalTarget = new FileTarget();
                fileLocalTarget.FileName         = Path.Combine(assemblyFolder, "Log.log");
                fileLocalTarget.Layout           = "${longdate}_${level}:  ${message} ${exception:format=ToString,StackTrace}";
                fileLocalTarget.MaxArchiveFiles  = 0;
                fileLocalTarget.ArchiveAboveSize = 410152;
                config.AddTarget("localFile", fileLocalTarget);
                var rule = new LoggingRule("*", LogLevel.Debug, fileLocalTarget);
                config.LoggingRules.Add(rule);
                LogManager.Configuration = config;

                // Серверный лог
                string serverLogPath    = Path.Combine(PikSettings.ServerShareSettingsFolder, @"AutoCAD_PIK_Manager\Logs");
                var    fileServerTarget = new FileTarget();
                fileServerTarget.FileName         = string.Format(@"{0}\{1}-{2}.log", serverLogPath, Environment.UserName, Environment.MachineName);
                fileServerTarget.Layout           = "${longdate}_${level}:  ${message} ${exception:format=ToString,StackTrace}";
                fileServerTarget.ArchiveAboveSize = 410152;
                fileServerTarget.MaxArchiveFiles  = 1;
                fileServerTarget.ArchiveNumbering = ArchiveNumberingMode.Rolling;
                config.AddTarget("serverFile", fileServerTarget);
                rule = new LoggingRule("*", LogLevel.Debug, fileServerTarget);
                config.LoggingRules.Add(rule);
                LogManager.Configuration = config;

                //AsyncTargetWrapper asyncWrapperSrvLog = new AsyncTargetWrapper(fileServerTarget);
                //asyncWrapperSrvLog.OverflowAction = AsyncTargetWrapperOverflowAction.Discard;
                //asyncWrapperSrvLog.QueueLimit = 100;
                //config.AddTarget("LogAsync", asyncWrapperSrvLog);
                //// Define rules
                //LoggingRule ruleSrvLogAsync = new LoggingRule("*", LogLevel.Error, asyncWrapperSrvLog);
                //config.LoggingRules.Add(ruleSrvLogAsync);

                // mail
                var mailTarget = new MailTarget();
                mailTarget.To         = "[email protected]; " + PikSettings.PikFileSettings.MailCADManager;
                mailTarget.From       = Environment.UserName + "@pik.ru";
                mailTarget.Subject    = string.Format("Сообщение от {0}, AutoCAD_PIK_Manager", Environment.UserName);
                mailTarget.SmtpServer = "ex20pik.picompany.ru";
                mailTarget.Body       = "${longdate} ${message} ${exception:format=ToString,StackTrace}";

                //config.AddTarget("mail", mailTarget);
                //rule = new LoggingRule("*", LogLevel.Error, mailTarget);
                //config.LoggingRules.Add(rule);

                // Set up asynchronous database logging assuming dbTarget is your existing target
                AsyncTargetWrapper asyncWrapperMail = new AsyncTargetWrapper(mailTarget);
                asyncWrapperMail.OverflowAction = AsyncTargetWrapperOverflowAction.Discard;
                asyncWrapperMail.QueueLimit     = 100;
                config.AddTarget("MailAsync", asyncWrapperMail);
                // Define rules
                LoggingRule ruleAsync = new LoggingRule("*", LogLevel.Error, asyncWrapperMail);
                config.LoggingRules.Add(ruleAsync);

                LogManager.Configuration = config;
            }
            catch
            {
            }
        }
Exemplo n.º 19
0
 public void UserLoggedIn(User user, [CallerFilePath] string callerPath = null, [CallerMemberName] string caller = null, [CallerLineNumber] int lineNumber = 0)
 {
     try
     {
         Facade.Log.CreateActionLog("UserLoggedIn", $"{callerPath} : {lineNumber}", caller, HttpContext.Current.Request.RawUrl, user.Name, user.ID);
         SendMail("[EgeMedya] Kullanıcı Girişi", $"{user.Name} ({user.Email}) kullanıcısı sisteme giriş yaptı.", MailTarget.SpecialSales(0));
     }
     catch (Exception exc)
     {
         Facade.Log.CreateErrorLog(ModuleName, "UserLoggedIn", "", exc, "");
     }
 }
Exemplo n.º 20
0
        /// <summary>
        /// Configure logging to email targets.
        ///
        /// Depending on the configuration, set up the logging via email. If no SmtpHost or no
        /// AdminEmailAdress is configured, nothing will be done. If they're set in the config file,
        /// a log target for messages with level "Fatal" will be configured. In addition, if the
        /// AdminDebugEmailAdress is set, another target for "Error" level messages is configured
        /// using this address as recipient.
        /// </summary>
        private void SetupMailLogging()
        {
            try {
                if (string.IsNullOrWhiteSpace(_config.SmtpHost) ||
                    string.IsNullOrWhiteSpace(_config.AdminEmailAdress))
                {
                    Log.Info("SMTP host or admin recipient unconfigured, disabling mail logging.");
                    return;
                }

                var subject = $"{ServiceName} - {_config.HostAlias} - Admin Notification";
                var body    = $"Notification from '{_config.HostAlias}' [{Environment.MachineName}] (via NLog)\n\n" +
                              $"{LogFormatDefault}\n\n" +
                              "NOTE: messages of the same log level won't be sent via email for the\n" +
                              $"next {_config.AdminNotificationDelta} minutes (or a service restart)," +
                              "please check the corresponding log file!";

                var logConfig = LogManager.Configuration;

                // "Fatal" target
                var mailTargetFatal = new MailTarget {
                    Name       = "mailfatal",
                    SmtpServer = _config.SmtpHost,
                    SmtpPort   = _config.SmtpPort,
                    From       = _config.EmailFrom,
                    To         = _config.AdminEmailAdress,
                    Subject    = subject,
                    Body       = body,
                };
                var mailTargetFatalLimited = new RateLimitWrapper {
                    Name           = "mailfatallimited",
                    MinLogInterval = _config.AdminNotificationDelta,
                    WrappedTarget  = mailTargetFatal
                };
                logConfig.AddTarget(mailTargetFatalLimited);
                logConfig.AddRuleForOneLevel(LogLevel.Fatal, mailTargetFatalLimited);

                // "Error" target
                if (!string.IsNullOrWhiteSpace(_config.AdminDebugEmailAdress))
                {
                    var mailTargetError = new MailTarget {
                        Name       = "mailerror",
                        SmtpServer = _config.SmtpHost,
                        SmtpPort   = _config.SmtpPort,
                        From       = _config.EmailFrom,
                        To         = _config.AdminDebugEmailAdress,
                        Subject    = subject,
                        Body       = body,
                    };
                    var mailTargetErrorLimited = new RateLimitWrapper {
                        Name           = "mailerrorlimited",
                        MinLogInterval = _config.AdminNotificationDelta,
                        WrappedTarget  = mailTargetError
                    };
                    logConfig.AddTarget(mailTargetErrorLimited);
                    logConfig.AddRuleForOneLevel(LogLevel.Error, mailTargetErrorLimited);
                    Log.Info("Configured mail notification for 'Error' messages to {0}", mailTargetError.To);
                }
                Log.Info("Configured mail notification for 'Fatal' messages to {0}", mailTargetFatal.To);
                LogManager.Configuration = logConfig;
            }
            catch (Exception ex) {
                Log.Error("SetupMailLogging(): {0}", ex.Message);
            }
        }
        public static void SetConfiguration()
        {
            string directory     = "${basedir}\\${shortdate}\\${shortdate}_";
            string logFileName   = "FileWithSomeCustomName";
            string globalLogFile = "GlobalLog";

            string basicLogLayout = "[${date}] [${level}] - ${message}";
            string errorLogLayout = "[${date}] [${level}] - ${callsite:className=True:methodName=True:includeNamespace=false} - ${message}";

            string filenameVariable = "${var:FILENAME}";

            string smtpUsername = "";
            string smtpPassword = "";

            LoggingConfiguration configuration = new LoggingConfiguration();

            #region targets configuration
            FileTarget errorFileTarget = new FileTarget()
            {
                Name   = "ErrorsPerFile",
                Layout = "[${date}] ${logger} - [${level}] - ${callsite} : ${message}"
            };

            errorFileTarget.FileName = $"{directory}{logFileName}.log";

            FileTarget globalFileTarget = new FileTarget()
            {
                Name   = "GlobalLogFile",
                Layout = "[${date}] ${logger} - [${level}] : ${message}"
            };

            globalFileTarget.FileName = $"{directory}{globalLogFile}.log";

            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget()
            {
                Name   = "ColoredConsoleGlobal",
                Layout = "[${date}] ${logger} - [${level}] : ${message}"
            };

            MailTarget mailTarget = new MailTarget()
            {
                SmtpServer         = "smtp.gmail.com",
                SmtpPort           = 587,
                EnableSsl          = true,
                SmtpAuthentication = SmtpAuthenticationMode.Basic,
                SmtpUserName       = smtpUsername,
                SmtpPassword       = smtpPassword,
                From        = smtpUsername,
                To          = smtpUsername,
                Subject     = "test nlog mail sending from code target",
                AddNewLines = true,
                Layout      = "[${date}] ${logger} - [${level}] : ${message}"
            };

            AsyncTargetWrapper mailAsync = new AsyncTargetWrapper()
            {
                WrappedTarget = mailTarget,
                Name          = "AsyncMail"
            };

            FileTarget errorLogPerAction = new FileTarget()
            {
                FileName = $"{directory}ErrorLogFor_${{var:FILENAME}}.log",
                Header   = $"Processing file: {filenameVariable}, error output:",
                Layout   = errorLogLayout
            };

            FileTarget globalLogPerAction = new FileTarget()
            {
                Header   = "Processing file: ${var:FILENAME}, log output:",
                FileName = $"{directory}GlobalLogFor_{filenameVariable}.log",
                Layout   = basicLogLayout
            };

            #endregion

            configuration.AddRule(LogLevel.Warn, LogLevel.Off, errorFileTarget);
            configuration.AddRuleForAllLevels(globalFileTarget);
            configuration.AddRuleForAllLevels(consoleTarget);
            //configuration.AddRuleForAllLevels(mailAsync);
            configuration.AddRuleForOneLevel(LogLevel.Error, errorLogPerAction);
            configuration.AddRuleForAllLevels(globalLogPerAction);

            LogManager.Configuration = configuration;
        }
Exemplo n.º 22
0
        public AutomationLogging()
        {
            string resultFolder = @"C:/WDTF/TestResult";
            string asm          = Assembly.GetCallingAssembly().FullName;
            string logFormat    = string.Format("{0:yyyy-MM-dd-hh-mm-ss}", DateTime.Now);

            newLocationInResultFolder = resultFolder + "/" + currentGuid + "_" + logFormat;
            DirectoryInfo directoryInfo = new DirectoryInfo(newLocationInResultFolder);

            if (!directoryInfo.Exists)
            {
                System.IO.Directory.CreateDirectory(newLocationInResultFolder);
            }
            LoggingConfiguration config = new LoggingConfiguration();


            //===========================================================================================//
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget
            {
                Layout = "${time} | ${level}  | ${stacktrace::topFrames=2}|${message} "
            };

            config.AddTarget("console", consoleTarget);
            LoggingRule consoleInfo = new LoggingRule("*", NLog.LogLevel.Info, consoleTarget);

            config.LoggingRules.Add(consoleInfo);
            //===========================================================================================//
            FileTarget fileTarget = new FileTarget
            {
                Layout   = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} ",
                FileName = newLocationInResultFolder + "/" + className + "_" + logFormat + DateTime.Now.Second + ".log"
            };

            config.AddTarget("file", fileTarget);
            LoggingRule fileInfo = new LoggingRule("*", NLog.LogLevel.Info, fileTarget);

            config.LoggingRules.Add(fileInfo);
            //===========================================================================================//
            TraceTarget traceTarget = new TraceTarget
            {
                Layout = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} "
            };

            //===========================================================================================//
            MailTarget mailTarget = new MailTarget
            {
                Name               = "gmail",
                SmtpServer         = "smtp.gmail.com",
                SmtpPort           = 465,
                SmtpAuthentication = SmtpAuthenticationMode.Basic,
                SmtpUserName       = "******",
                SmtpPassword       = "******",
                EnableSsl          = true,
                From               = "*****@*****.**",
                To = "*****@*****.**",
                CC = ""
            };
            LoggingRule mailInfo = new LoggingRule("*", NLog.LogLevel.Info, mailTarget);

            config.LoggingRules.Add(mailInfo);

            //===========================================================================================//
            DatabaseTarget dbTarget = new DatabaseTarget();

            //===========================================================================================//

            // Step 4. Define rules
            LogManager.Configuration = config;
        }
Exemplo n.º 23
0
        static Log()
        {
            var config = new LoggingConfiguration();

            var fileTarget = new FileTarget
            {
                Name     = "FileTarget",
                FileName = "${basedir}/Logs/${shortdate}.log",
                Layout   =
                    @"${longdate} ::: Exception Type: ${exception:format=Type} ::: Message: ${message} ::: ${exception:format=tostring,Data:maxInnerExceptionLevel=10}${newline}"
            };

            config.AddTarget("File", fileTarget);

            DatabaseTarget dataBaseTarget = null;

            if (ConfigurationManager.ConnectionStrings["Updater"] != null)
            {
                dataBaseTarget = new DatabaseTarget
                {
                    Name             = "DatabaseTarget",
                    ConnectionString = ConfigurationManager.ConnectionStrings["Updater"].ConnectionString,
                    CommandText      = @"INSERT INTO [UnhandledException] 
                                (Id, Date, Thread, Level, Logger, Message, Exception, Stack, ExceptionType) 
                                VALUES
                                ((SELECT NEWID()), (SELECT GETDATE()), @thread, @level, @logger, @message, @exception, @stack, @exceptionType)"
                };

                dataBaseTarget.Parameters.Add(new DatabaseParameterInfo("@thread", new SimpleLayout("${threadid}")));
                dataBaseTarget.Parameters.Add(new DatabaseParameterInfo("@level", new SimpleLayout("${level}")));
                dataBaseTarget.Parameters.Add(new DatabaseParameterInfo("@logger", new SimpleLayout("${logger}")));
                dataBaseTarget.Parameters.Add(new DatabaseParameterInfo("@message", new SimpleLayout("${message}")));
                dataBaseTarget.Parameters.Add(new DatabaseParameterInfo("@exception", new SimpleLayout("${exception}")));
                dataBaseTarget.Parameters.Add(new DatabaseParameterInfo("@stack",
                                                                        new SimpleLayout("${exception:format=tostring,Data:maxInnerExceptionLevel=10}${newline}")));
                dataBaseTarget.Parameters.Add(new DatabaseParameterInfo("@exceptionType",
                                                                        new SimpleLayout("${exception:format=Type}")));

                config.AddTarget("DataBase", dataBaseTarget);
            }

            var mailTarget = new MailTarget
            {
                Name = "MailTarget",
                Html = true,
                Body =
                    "${longdate} ::: Exception Type: ${exception:format=Type} ::: Message: ${message} ::: ${exception:format=tostring,Data:maxInnerExceptionLevel=10}${newline}",
                SmtpServer         = ConfigurationManager.AppSettings["SmtpServer"],
                From               = ConfigurationManager.AppSettings["EmailSender"],
                Encoding           = Encoding.UTF8,
                To                 = ConfigurationManager.AppSettings["EmailReceiver"],
                EnableSsl          = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]),
                SmtpPort           = Convert.ToInt32(ConfigurationManager.AppSettings["SendingPort"]),
                SmtpUserName       = ConfigurationManager.AppSettings["EmailSender"],
                SmtpPassword       = ConfigurationManager.AppSettings["PasswordSender"],
                SmtpAuthentication = SmtpAuthenticationMode.Basic,
                Subject            = "Updater ${level}"
            };

            config.AddTarget("Mailing", mailTarget);

            var eventLogTarget = new EventLogTarget
            {
                Name   = "EventLogTarget",
                Layout =
                    @"${longdate} ::: Exception Type: ${exception:format=Type} ::: Message: ${message} ::: ${exception:format=tostring,Data:maxInnerExceptionLevel=10}${newline}",
                Log    = "Application",
                Source = "Updater"
            };

            config.AddTarget("EventLog", eventLogTarget);

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

            if (dataBaseTarget != null)
            {
                config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, dataBaseTarget));
            }

            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, mailTarget));
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, eventLogTarget));

            LogManager.Configuration = config;
            Instance = LogManager.GetCurrentClassLogger();
        }
Exemplo n.º 24
0
Arquivo: WDNav.cs Projeto: subha9/WDTF
        public AutomationLogging()
        {
            string resultFolder = @"C:/WDTF/TestResult";
            string asm          = Assembly.GetCallingAssembly().FullName;
            string logFormat    = string.Format("{0:yyMMddhhmmss}", DateTime.Now);

            newLocationInResultFolder = resultFolder + "/" + currentGuid + "_" + logFormat;
            DirectoryInfo directoryInfo = new DirectoryInfo(newLocationInResultFolder);

            if (!directoryInfo.Exists)
            {
                System.IO.Directory.CreateDirectory(newLocationInResultFolder);
            }
            //FileInfo[] fileInformation = directoryInfo.GetFiles();
            //foreach (FileInfo item in fileInformation)
            //{
            //    item.Delete();
            //}
            LoggingConfiguration config = new LoggingConfiguration();
            //{TestName}_TIME.htm
            // string logFormat = string.Format("{0:yyMMddhhmmss}", DateTime.Now);


            //===========================================================================================//
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();

            consoleTarget.Layout = "${time} | ${level}  | ${stacktrace::topFrames=2}|${message} ";
            config.AddTarget("console", consoleTarget);
            LoggingRule consoleInfo = new LoggingRule("*", LogLevel.Info, consoleTarget);

            config.LoggingRules.Add(consoleInfo);
            //===========================================================================================//
            FileTarget fileTarget = new FileTarget();

            fileTarget.Layout   = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} ";
            fileTarget.FileName = newLocationInResultFolder + "/" + className + "_" + logFormat + ".txt";
            config.AddTarget("file", fileTarget);
            LoggingRule fileInfo = new LoggingRule("*", LogLevel.Info, fileTarget);

            config.LoggingRules.Add(fileInfo);
            //===========================================================================================//
            TraceTarget traceTarget = new TraceTarget();

            traceTarget.Layout = "${time} | ${level}  | ${stacktrace:topFrames=2} | ${message} ";

            //===========================================================================================//
            MailTarget mailTarget = new MailTarget();

            mailTarget.Name               = "gmail";
            mailTarget.SmtpServer         = "smtp.gmail.com";
            mailTarget.SmtpPort           = 465;
            mailTarget.SmtpAuthentication = SmtpAuthenticationMode.Basic;
            mailTarget.SmtpUserName       = "******";
            mailTarget.SmtpPassword       = "******";
            mailTarget.EnableSsl          = true;
            mailTarget.From               = "*****@*****.**";
            mailTarget.To = "*****@*****.**";
            mailTarget.CC = "";
            LoggingRule mailInfo = new LoggingRule("*", LogLevel.Info, mailTarget);

            config.LoggingRules.Add(mailInfo);

            //===========================================================================================//
            DatabaseTarget dbTarget = new DatabaseTarget();

            //===========================================================================================//

            // Step 4. Define rules
            LogManager.Configuration = config;
        }