Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            var props = new NameValueCollection();
            props["configType"] = "EXTERNAL";
            LogManager.Adapter = new Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter(props);

            var layout = new log4net.Layout.PatternLayout("%d [%t] %-5p %c [%x] <%X{auth}> - %m%n");
            var level = log4net.Core.Level.Debug;

            var appender = new log4net.Appender.ConsoleAppender
            {
                Layout = layout,
                Threshold = level
            };
            log4net.Config.BasicConfigurator.Configure(appender);

            if(!MsmqInstallation.IsInstallationGood())
            {
                Console.WriteLine("MSMQ is not configured correctly for use with NServiceBus");

                if(!args.ToList().Contains("/i"))
                {
                    Console.WriteLine("Please run with /i to reconfigure MSMQ");
                    return;
                }
            }
            MsmqInstallation.StartMsmqIfNecessary();

            DtcUtil.StartDtcIfNecessary();

            PerformanceCounterInstallation.InstallCounters();
        }
Ejemplo n.º 2
0
        //configure log4Net via code instead of xml
        public static void InitLog(string completeLogFile)
        {
            _filePath = completeLogFile;

            var hierarchy = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();
            hierarchy.Root.RemoveAllAppenders();

            var pl = new log4net.Layout.PatternLayout { ConversionPattern = DefaultConversionPatern };
            pl.ActivateOptions();
            var fileAppender = new RollingFileAppender()
            {
                AppendToFile = true,
                LockingModel = new FileAppender.MinimalLock(),
                File = _filePath,
                Layout = pl,
            };

            fileAppender.MaxFileSize = 10 * 1024 * 1024;
            fileAppender.RollingStyle = RollingFileAppender.RollingMode.Size;
            fileAppender.MaxSizeRollBackups = 5;

            fileAppender.ActivateOptions();

            BasicConfigurator.Configure(fileAppender);

            _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// constructor that initialize logger name, file name and log level
        /// </summary>
        public CLogger(string sLoggerName, string sFilename, int iLogLevel)
        {
            ILog oLogger = LogManager.GetLogger(sLoggerName);
            string sLogFileName = string.Empty;
            sLogFileName = GetLogFileName(sFilename);

            m_oFPLogger = (log4net.Repository.Hierarchy.Logger)oLogger.Logger;
            log4net.Appender.RollingFileAppender oFPAppender = new RollingFileAppender();
            oFPAppender.File = sLogFileName;
            oFPAppender.MaxSizeRollBackups = 100;
            oFPAppender.MaximumFileSize = "1MB";
            oFPAppender.RollingStyle = RollingFileAppender.RollingMode.Size;
            oFPAppender.StaticLogFileName = true;
            oFPAppender.AppendToFile = true;
            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout();
            layout.ConversionPattern = "%d %-5p - %m%n%exception";
            layout.ActivateOptions();
            oFPAppender.Layout = layout;
            oFPAppender.ActivateOptions();
            /** Programmatically configuration will not work it it is not set true**/
            m_oFPLogger.Hierarchy.Configured = true;

            try
            {
                m_oFPLogger.AddAppender(oFPAppender);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to Add Appender", ex);
            }
            m_oFPLogger.Hierarchy.Root.Level = m_oFPLogger.Hierarchy.LevelMap[GetLogLevel(iLogLevel)];

            oLogger = null;
        }
Ejemplo n.º 4
0
        public Log4NetLogFactory(LogFileSettings settings)
        {
            var patternLayout = new log4net.Layout.PatternLayout(
                "%date [%thread] %level %logger - %message%newline");
            patternLayout.ActivateOptions();

            RollingFileAppender appender
                = new RollingFileAppender
                      {
                          Name = "rolling-appender",
                          File = Path.Combine(settings.DirectoryPath, settings.NamePrefix + ".log"),
                          AppendToFile = true,
                          MaxSizeRollBackups = 10,
                          RollingStyle = RollingFileAppender.RollingMode.Date,
                          Layout = patternLayout,
                          LockingModel = new FileAppender.MinimalLock()
                      };
            appender.ActivateOptions();


            log4net.Config.BasicConfigurator.Configure(appender);

            Hierarchy h = (Hierarchy)LogManager.GetRepository();
            Logger rootLogger = h.Root;
            rootLogger.Level = h.LevelMap[ConvertLogLevel(settings.Level).ToString().ToUpper()];
        }
Ejemplo n.º 5
0
        public void Configure()
        {
            if (_configured) return;

            lock (LockObject)
            {
                if (_configured) return;

                var logger = (Hierarchy) LogManager.CreateRepository(RepositoryName);
                logger.Root.RemoveAllAppenders();
                logger.Root.Level = GetLevel();

                var layout = new log4net.Layout.PatternLayout
                {
                    ConversionPattern =
                        "%date [%thread] %-5level %logger [%property] - %message%newline"
                };
                layout.ActivateOptions();

                var fileAppender = new FileAppender
                {
                    AppendToFile = true,
                    LockingModel = new FileAppender.MinimalLock(),
                    File = _configuration.InternalLogLocation,
                    Layout = layout,
                    ImmediateFlush = true
                };
                fileAppender.ActivateOptions();

                BasicConfigurator.Configure(logger, fileAppender);

                _configured = true;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Adds the email logging appender.
        /// </summary>
        public static void ConfigureEmailLoggingAppender()
        {
            var hier =
            (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();

            if (hier == null) return;

            var appender = (SmtpAppender)hier.Root.GetAppender("SmtpAppender") ?? new SmtpAppender();

            appender.Name = "SmtpAppender";
            appender.From = HostSettingManager.Get(HostSettingNames.HostEmailAddress, string.Empty);
            appender.To = HostSettingManager.Get(HostSettingNames.ErrorLoggingEmailAddress, string.Empty);
            appender.Subject = "BugNET Error";
            appender.SmtpHost = HostSettingManager.SmtpServer;
            appender.Priority = System.Net.Mail.MailPriority.High;
            appender.Threshold = log4net.Core.Level.Error;
            appender.BufferSize = 0;

            //create patternlayout
            var patternLayout = new
                log4net.Layout.PatternLayout("%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline");

            patternLayout.ActivateOptions();
            appender.Layout = patternLayout;
            appender.ActivateOptions();

            //add appender to root logger
            hier.Root.AddAppender(appender);
        }
Ejemplo n.º 7
0
        public static void InitLog(string completeLogFile, bool externalConsole)
        {
            _filePath = completeLogFile;

            var hierarchy = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();
            hierarchy.Root.RemoveAllAppenders();

            var pl = new log4net.Layout.PatternLayout { ConversionPattern = DefaultConversionPatern };
            pl.ActivateOptions();
            var fileAppender = new log4net.Appender.FileAppender
            {
                AppendToFile = true,
                LockingModel = new log4net.Appender.FileAppender.MinimalLock(),
                File = _filePath,
                Layout = pl
            };
            fileAppender.ActivateOptions();

            log4net.Config.BasicConfigurator.Configure(fileAppender);

            _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            if (externalConsole)
            {
                AddLogToConsole(false);
            }
        }
Ejemplo n.º 8
0
 public AzureAppender(bool initializeDiagnostics)
 {
     this.InitializeDiagnostics = initializeDiagnostics;
     ScheduledTransferPeriod = GetScheduledTransferPeriod();
     Layout = new log4net.Layout.PatternLayout(GetLayout());
     Level = GetLevel();
 }
Ejemplo n.º 9
0
        private static void initializeLogging()
        {
            var thisFilename = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            var logFilename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(thisFilename, "txt"));

            var layout = new log4net.Layout.PatternLayout("%d [%t]%-5p %c [%x] - %m%n");
            layout.ActivateOptions();

            log4net.Config.BasicConfigurator.Configure(
                new log4net.Appender.FileAppender(
                    layout, logFilename));
        }
Ejemplo n.º 10
0
        public static void Configure()
        {
            if (isConfigured)
                return;

            var loggerName = "SBDIL";

            var logger = (log4net.Repository.Hierarchy.Logger)log4net.LogManager.GetRepository().GetLogger(loggerName);
            var ilogger = log4net.LogManager.GetRepository().GetLogger(loggerName);

            //Add the default log appender if none exist
            if(logger.Appenders.Count == 0)
            {
                var directoryName = "C:\\BarkLogs";

                //If the directory doesn't exist then create it
                if(!Directory.Exists(directoryName))
                    Directory.CreateDirectory(directoryName);

                var fileName = Path.Combine(directoryName, DateTime.Now.ToString("yyyyMMddTHHmmss") + ".txt");

                //Create the rolling file appender
                var appender = new log4net.Appender.RollingFileAppender();
                appender.Name = "RollingFileAppender";
                appender.File = fileName;
                appender.StaticLogFileName = true;
                appender.AppendToFile = false;
                appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Size;
                appender.MaxSizeRollBackups = 10;
                appender.MaximumFileSize = "10MB";
                appender.PreserveLogFileNameExtension = true;

                //Configure the layout of the trace message write
                var layout = new log4net.Layout.PatternLayout()
                {
                    ConversionPattern = "%date{MM/dd/yyyy hh:mm:ss.fff} - %message%newline"
                };
                appender.Layout = layout;
                layout.ActivateOptions();

                //Let log4net configure itself based on the values provided
                appender.ActivateOptions();
                log4net.Config.BasicConfigurator.Configure(appender);
            }

            iLog = LogManager.GetLogger(loggerName);
            isConfigured = true;
        }
        public void NamedPatternConverterWithPrecisionMinus2ShouldStripLastTwoElements()
        {
            StringAppender stringAppender = new StringAppender();

            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout();
            layout.AddConverter("message-as-name", typeof(MessageAsNamePatternConverter));
            layout.ConversionPattern = "%message-as-name{-2}";
            layout.ActivateOptions();
            stringAppender.Layout = layout;
            ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());

            BasicConfigurator.Configure(rep, stringAppender);
            ILog log1 = LogManager.GetLogger(rep.Name, "TestAddingCustomPattern");

            log1.Info("Tw.o.Dots");
            Assert.AreEqual("Tw/o", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            log1.Info("NoDots");
            Assert.AreEqual("NoDots", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            log1.Info("One.Dot");
            Assert.AreEqual("One/Dot", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            log1.Info("TrailingDot.");
            Assert.AreEqual("TrailingDot", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            log1.Info(".LeadingDot");
            Assert.AreEqual("LeadingDot", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            // empty string and other evil combinations as tests for of-by-one mistakes in index calculations
            log1.Info(string.Empty);
            Assert.AreEqual(string.Empty, stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            log1.Info("x");
            Assert.AreEqual("x", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            log1.Info(".");
            Assert.AreEqual(".", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();
        }
        public void NamedPatternConverterWithPrecision1ShouldStripLeadingStuffIfPresent()
        {
            StringAppender stringAppender = new StringAppender();
            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout();
            layout.AddConverter("message-as-name", typeof(MessageAsNamePatternConverter));
            layout.ConversionPattern = "%message-as-name{1}";
            layout.ActivateOptions();
            stringAppender.Layout = layout;
            ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
            BasicConfigurator.Configure(rep, stringAppender);
            ILog log1 = LogManager.GetLogger(rep.Name, "TestAddingCustomPattern");

            log1.Info("NoDots");
            Assert.AreEqual("NoDots", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            log1.Info("One.Dot");
            Assert.AreEqual("Dot", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            log1.Info("Tw.o.Dots");
            Assert.AreEqual("Dots", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            //This behaviour differs from the log4net source.
            log1.Info("TrailingDot.");
            Assert.AreEqual("TrailingDot", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            log1.Info(".LeadingDot");
            Assert.AreEqual("LeadingDot", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            // empty string and other evil combinations as tests for of-by-one mistakes in index calculations
            log1.Info(string.Empty);
            Assert.AreEqual(string.Empty, stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            log1.Info("x");
            Assert.AreEqual("x", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();

            log1.Info(".");
            Assert.AreEqual(".", stringAppender.GetString(), "%message-as-name not registered");
            stringAppender.Reset();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// This method is used to create the appender
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="appenderName"></param>
        /// <returns></returns>
        private log4net.Appender.FileAppender CreateAppender(string fileName, string appenderName)
        {
            //log4net.Appender.FileAppender fileAppender = new log4net.Appender.FileAppender();
            log4net.Appender.RollingFileAppender fileAppender = new log4net.Appender.RollingFileAppender();

            log4net.Layout.PatternLayout patternLayOut = new log4net.Layout.PatternLayout();
            patternLayOut.Header            = ""; //System.Environment.NewLine + "---Starts Here---" + System.Environment.NewLine;
            patternLayOut.Footer            = ""; //
            patternLayOut.ConversionPattern = "%d %m%n";

            //patternLayOut.ConversionPattern = "";
            patternLayOut.ActivateOptions();


            string path = AppDomain.CurrentDomain.BaseDirectory + @"\Log"; //System.Windows.Forms.Application.StartupPath + @"\Log";

            System.IO.DirectoryInfo info = new DirectoryInfo(path);

            if (!info.Exists)
            {
                info.Create();
            }
            string[] file = fileName.Split('\\');


            fileAppender.Layout = patternLayOut;


            fileAppender.AppendToFile    = true;
            fileAppender.MaximumFileSize = Parameter.LOGGING_FILE_SIZE.Trim().Equals("") ? DefaultMaximumFileSize : Parameter.LOGGING_FILE_SIZE;

            fileAppender.MaxSizeRollBackups = 10;
            fileAppender.StaticLogFileName  = true;
            fileAppender.RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Size;

            //fileAppender.DatePattern = ".yyyyMMdd'.log'";
            //fileAppender.File = path + "\\" + file[file.Length - 1].Split('.')[0];

            fileAppender.File = path + "\\" + file[file.Length - 1];
            fileAppender.Name = appenderName;

            fileAppender.LockingModel = new log4net.Appender.FileAppender.MinimalLock();
            fileAppender.ActivateOptions();

            return(fileAppender);
        }
Ejemplo n.º 14
0
 public static void AddLogToConsole(bool basicConfig)
 {
     AllocConsole();
     var appender = new log4net.Appender.ConsoleAppender();
     var layout = new log4net.Layout.PatternLayout
     {
         ConversionPattern = DefaultConversionPatern,
         Header = "Time;Level;Description;"
     };
     layout.ActivateOptions();
     appender.Layout = layout;
     appender.ActivateOptions();
     if (basicConfig)
         log4net.Config.BasicConfigurator.Configure(appender);
     else
         ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.AddAppender(appender);
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Adds the email logging appender.
        /// </summary>
        public static void ConfigureEmailLoggingAppender()
        {
            var hier =
                (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();

            if (hier == null)
            {
                return;
            }

            var appender = (SmtpAppender)hier.Root.GetAppender("SmtpAppender") ?? new SmtpAppender();

            appender.Name           = "SmtpAppender";
            appender.From           = HostSettingManager.Get(HostSettingNames.HostEmailAddress, string.Empty);
            appender.To             = HostSettingManager.Get(HostSettingNames.ErrorLoggingEmailAddress, string.Empty);
            appender.Subject        = "BugNET Error";
            appender.SmtpHost       = HostSettingManager.SmtpServer;
            appender.Port           = int.Parse(HostSettingManager.Get(HostSettingNames.SMTPPort));
            appender.Authentication = SmtpAppender.SmtpAuthentication.None;
            appender.Username       = string.Empty;
            appender.Password       = string.Empty;
            appender.EnableSsl      = Boolean.Parse(HostSettingManager.Get(HostSettingNames.SMTPUseSSL));

            if (Convert.ToBoolean(HostSettingManager.Get(HostSettingNames.SMTPAuthentication)))
            {
                appender.Authentication = SmtpAppender.SmtpAuthentication.Basic;
                appender.Username       = String.Format("{0}\\{1}", HostSettingManager.Get(HostSettingNames.SMTPDomain, string.Empty), HostSettingManager.Get(HostSettingNames.SMTPUsername, string.Empty));
                appender.Password       = HostSettingManager.Get(HostSettingNames.SMTPPassword, string.Empty);
            }

            appender.Priority   = System.Net.Mail.MailPriority.High;
            appender.Threshold  = log4net.Core.Level.Error;
            appender.BufferSize = 0;

            //create patternlayout
            var patternLayout = new
                                log4net.Layout.PatternLayout("%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline");

            patternLayout.ActivateOptions();
            appender.Layout = patternLayout;
            appender.ActivateOptions();

            //add appender to root logger
            hier.Root.AddAppender(appender);
        }
Ejemplo n.º 16
0
        public static log4net.Appender.IAppender CreateFileAppender(string name, string fileName)
        {
            log4net.Appender.FileAppender appender = new
                                                     log4net.Appender.FileAppender();
            appender.Name         = name;
            appender.File         = fileName;
            appender.AppendToFile = true;

            log4net.Layout.PatternLayout layout = new
                                                  log4net.Layout.PatternLayout();
            //layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n";
            layout.ActivateOptions();

            appender.Layout = layout;
            appender.ActivateOptions();

            return(appender);
        }
Ejemplo n.º 17
0
        protected void ConfigureLogger()
        {
            log4net.Layout.ILayout        layout;
            log4net.Appender.FileAppender appender;

            layout   = new log4net.Layout.PatternLayout("\v%date{ISO8601} %logger %-5level: %message%newline");
            appender = new log4net.Appender.FileAppender();
            appender.AppendToFile    = true;
            appender.Encoding        = Encoding.UTF8;
            appender.File            = this._path;
            appender.ImmediateFlush  = true;
            appender.Layout          = layout;
            appender.LockingModel    = new log4net.Appender.FileAppender.MinimalLock();
            appender.Name            = "FileAppender";
            appender.SecurityContext = new log4net.Util.WindowsSecurityContext();
            appender.Threshold       = log4net.Core.Level.All;
            log4net.Config.BasicConfigurator.Configure(appender);
        }
Ejemplo n.º 18
0
        public static void ConfigLogging()
        {
            FileAppender fileAppender = new FileAppender();
            fileAppender.AppendToFile = true;
            fileAppender.LockingModel = new FileAppender.MinimalLock();
            fileAppender.File = Params.logFile;

            log4net.Layout.PatternLayout pl = new log4net.Layout.PatternLayout();
            //d:timestamp t:thread p:level c:Class name m:message n:new line
            //pl.ConversionPattern = "%d [%2%t] %-5p [%-10c] %m%n";
            pl.ConversionPattern = "%d %-5p [%-10c] %m%n";
            pl.ActivateOptions();

            fileAppender.Layout = pl;
            fileAppender.ActivateOptions();

            log4net.Config.BasicConfigurator.Configure(fileAppender);
        }
Ejemplo n.º 19
0
 public static void InitLogger()
 {
     //NTT : let's configure log4net for coloredconsole output and debug trace
     //var layout = new log4net.Layout.SimpleLayout();
     //var layout = new log4net.Layout.PatternLayout("%-4timestamp [%thread] %-5level %logger %ndc - %message%newline");
     var layout = new log4net.Layout.PatternLayout("%date %-5level %message%newline");
     var ta = new TraceAppender { Layout = layout };
     var ca = new ColoredConsoleAppender { Threshold = Level.All, Layout = layout };
     var cca = new ColoredConsoleAppender { Threshold = Level.All, Layout = layout };
     cca.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Debug, ForeColor = ColoredConsoleAppender.Colors.Cyan | ColoredConsoleAppender.Colors.HighIntensity });
     cca.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Info, ForeColor = ColoredConsoleAppender.Colors.Green | ColoredConsoleAppender.Colors.HighIntensity });
     cca.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Warn, ForeColor = ColoredConsoleAppender.Colors.Purple | ColoredConsoleAppender.Colors.HighIntensity });
     cca.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Error, ForeColor = ColoredConsoleAppender.Colors.Red | ColoredConsoleAppender.Colors.HighIntensity });
     cca.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Fatal, ForeColor = ColoredConsoleAppender.Colors.White | ColoredConsoleAppender.Colors.HighIntensity, BackColor = ColoredConsoleAppender.Colors.Red });
     cca.ActivateOptions();
     BasicConfigurator.Configure(cca);
     Logger l = (Logger)log.Logger;
     l.AddAppender(ta);
 }
Ejemplo n.º 20
0
        // Create a new file appender
        public static log4net.Appender.IAppender CreateFileAppender(string name,
        string fileName)
        {
            log4net.Appender.FileAppender appender = new
              log4net.Appender.FileAppender();
            appender.Name = name;
            appender.File = fileName;
            appender.AppendToFile = true;

            log4net.Layout.PatternLayout layout = new
            log4net.Layout.PatternLayout();
            layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n";
            layout.ActivateOptions();

            appender.Layout = layout;
            appender.ActivateOptions();

            return appender;
        }
Ejemplo n.º 21
0
        private static ILog getDefaultLogger(String name)
        {
            ILog r = LogManager.GetCurrentLoggers().SingleOrDefault(x => x.Logger.Name == name);

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

            Hierarchy hierarchy = (Hierarchy)r;

            log4net.Appender.ColoredConsoleAppender appender = new
                                                               log4net.Appender.ColoredConsoleAppender();
            appender.Name = name;

            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout();
            layout.ConversionPattern = "%-4timestamp [%thread] %-5level %logger %ndc - %message%newline";
            layout.ActivateOptions();

            appender.Layout = layout;

            log4net.Filter.LevelRangeFilter filter = new log4net.Filter.LevelRangeFilter();
            filter.LevelMax = log4net.Core.Level.Fatal;
            filter.LevelMin = log4net.Core.Level.Debug;

            appender.AddFilter(filter);
            appender.ActivateOptions();

            hierarchy.Root.AddAppender(appender);

            hierarchy.Root.Level = log4net.Core.Level.All;
            hierarchy.Configured = true;

            DummyLogger dummyILogger = new DummyLogger(name);

            dummyILogger.Hierarchy = hierarchy;
            dummyILogger.Level     = log4net.Core.Level.All;

            dummyILogger.AddAppender(appender);

            return(new log4net.Core.LogImpl(dummyILogger));;
        }
Ejemplo n.º 22
0
        public void Configure(IEnumerable <KeyValuePair <string, string> > config = null)
        {
            _config = config ?? new Dictionary <string, string>();

            var layoutPattern   = GetValue("LayoutPattern") ?? "%level - %message%newline";
            var identityPattern = GetValue("IdentityPattern") ?? "%date{yyyy-MM-ddTHH:mm:ss.ffffffzzz} %P{log4net:HostName} %logger";
            var remoteServer    = GetValue("RemoteServer") ?? "logs4.papertrailapp.com";
            var remotePort      = GetValue("RemotePort") ?? "0000";
            var logFile         = GetValue("LogFile") ?? "log.txt";


            var layout = new Fr8PatternLayout()
            {
                ConversionPattern = layoutPattern
            };

            var identity = new log4net.Layout.PatternLayout()
            {
                ConversionPattern = identityPattern
            };

            var fileLayout = new log4net.Layout.PatternLayout()
            {
                ConversionPattern = identityPattern + " : " + layoutPattern
            };

            var appender = new Fr8RemoteSyslogAppender()
            {
                Layout = layout,
                //identity rendering dows not working properly
                //Identity = identity,
                RemoteAddress = remoteServer,
                RemotePort    = int.Parse(remotePort)
            };



            var fap = new log4net.Appender.FileAppender(fileLayout, logFile);

            log4net.Config.BasicConfigurator.Configure(appender, fap);
        }
Ejemplo n.º 23
0
        private IAppender CreateRollingFileAppender(string name, string fileName)
        {
            log4net.Appender.RollingFileAppender appender = new RollingFileAppender();

            appender.Name         = name;
            appender.File         = fileName;
            appender.AppendToFile = true;
            appender.LockingModel = new FileAppender.MinimalLock();
            //appender.ImmediateFlush = true;
            appender.RollingStyle      = RollingFileAppender.RollingMode.Date;
            appender.StaticLogFileName = true;

            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout();
            layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n";
            layout.ActivateOptions();

            appender.Encoding = Encoding.UTF8;
            appender.Layout   = layout;
            appender.ActivateOptions();

            return(appender);
        }
Ejemplo n.º 24
0
        private static void AddConsoleAppender()
        {
            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout
            {
                ConversionPattern = "%message%newline"
            };
            layout.ActivateOptions();

            var appender = new log4net.Appender.ManagedColoredConsoleAppender()
            {
                Threshold = Level.All
            };

            appender.Name   = "Console";
            appender.Layout = layout;
            appender.ActivateOptions();

            var l = (log4net.Repository.Hierarchy.Logger)log.Logger;

            l.AddAppender(appender);
            l.Repository.Configured = true;
        }
Ejemplo n.º 25
0
        /// <summary>
        /// add rolling file appender
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="patternStr"></param>
        public static void AddFileLogger(String filename, String patternStr)
        {
            if (!String.IsNullOrEmpty(filename))
            {
                if (String.IsNullOrEmpty(patternStr))
                {
                    patternStr = "%message%newline";
                }

                log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(patternStr);

                log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
                appender.RollingStyle      = log4net.Appender.RollingFileAppender.RollingMode.Date;
                appender.Layout            = layout;
                appender.File              = filename;
                appender.DatePattern       = "\"_\"yyyyMMdd\".txt\"";
                appender.StaticLogFileName = false;
                appender.ActivateOptions();

                m_Appenders.Add(appender);
            }
        }
Ejemplo n.º 26
0
        public static void AddLogToConsole(bool basicConfig)
        {
            AllocConsole();
            var appender = new log4net.Appender.ConsoleAppender();
            var layout   = new log4net.Layout.PatternLayout
            {
                ConversionPattern = DefaultConversionPatern,
                Header            = "Time;Level;Description;"
            };

            layout.ActivateOptions();
            appender.Layout = layout;
            appender.ActivateOptions();
            if (basicConfig)
            {
                log4net.Config.BasicConfigurator.Configure(appender);
            }
            else
            {
                ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.AddAppender(appender);
            }
        }
Ejemplo n.º 27
0
        private static RollingFileAppender GetNewFileApender()
        {
            var appender = new RollingFileAppender
            {
                Name               = "Ecoscan.Log",
                File               = "Log.txt",
                AppendToFile       = true,
                MaxSizeRollBackups = 10,
                MaximumFileSize    = "10MB",
                StaticLogFileName  = true,
                RollingStyle       = RollingFileAppender.RollingMode.Size,
                DatePattern        = "yyyy.MM.dd"
            };

            var layout = new log4net.Layout.PatternLayout("%d %p %m%n");

            appender.Layout = layout;

            layout.ActivateOptions();
            appender.ActivateOptions();
            return(appender);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Create File appender, This appender is responsible to write stream of data when invoked, in
        /// our case, this appender is handeled my the Bufferappender
        /// </summary>
        /// <param name="cacheName">Name of the file appender</param>
        /// <param name="fileName">Filename to which is to write logs</param>
        /// <returns>returns the created appender</returns>
        private log4net.Appender.IAppender CreateRollingFileAppender(string fileName, bool apiLogs)
        {
            log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
            appender.Name = "RollingFileAppender" + _loggerName;
            appender.File = fileName;
            //doesnt matter since all files are created with a new name
            appender.AppendToFile = true;

            appender.RollingStyle       = RollingFileAppender.RollingMode.Size;
            appender.MaximumFileSize    = "5MB";
            appender.MaxSizeRollBackups = -1;

            appender.Threshold = log4net.Core.Level.All;

            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout();

            //DateSpace == 23 || appdomain == 25 || Longest thread.Name == 34 || Leve max length == 5 ||
            if (!apiLogs)
            {
                layout.ConversionPattern = "%-27date{ISO8601}" + "\t%-45.42appdomain" + "\t%-43logger" + "\t%-42thread" + "\t%-9level" + "\t%message" + "%newline";

                layout.Header = "TIMESTAMP                  \tAPPDOMAIN                                    \tLOGGERNAME                                 \tTHREADNAME                                \tLEVEL    \tMESSAGE\r\n";
            }
            else
            {
                appender.Name            = LoggerNames.APILogs.ToString().ToLower() + "_" + appender.Name;
                layout.ConversionPattern = "%message" + "%newline";
                layout.Header            = "TIMESTAMP                     \t\t    SERVER              CLIENTIP            ProcessID           				\tExecutionTime   \tMethod                                          														 											             \t\t\tParameters                                                                                                                                                                                                                                 Exception\r\n";
            }


            layout.Footer = "END \n";

            layout.ActivateOptions();
            appender.Layout = layout;
            appender.ActivateOptions();

            return(appender);
        }
        private static log4net.ILog CreateLog4NetLogger()
        {
            var hierarchy     = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository();
            var patternLayout = new log4net.Layout.PatternLayout()
            {
                ConversionPattern = "%date %-5level %logger %message%newline"
            };

            patternLayout.ActivateOptions();

            var roller = new log4net.Appender.FileAppender
            {
                File         = "log4net.txt",
                Layout       = patternLayout,
                LockingModel = new log4net.Appender.FileAppender.MinimalLock()
            };

            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);
            hierarchy.Root.Level = log4net.Core.Level.Info;
            hierarchy.Configured = true;
            return(log4net.LogManager.GetLogger(typeof(FileLoggingBenchmark)));
        }
Ejemplo n.º 30
0
        private static void SetUpConsoleLogger()
        {
            string consolePattern = "%message%newline";

            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(consolePattern);
            layout.Header = "";
            layout.Footer = "";
            layout.ActivateOptions();

            log4net.Appender.ConsoleAppender consoleAppender = new log4net.Appender.ConsoleAppender();
            //consoleAppender.ErrorHandler = new LoggingErrorHandler();
            consoleAppender.Name      = "Console appender";
            consoleAppender.Threshold = log4net.Core.Level.Warn;
            consoleAppender.Layout    = layout;
            consoleAppender.Target    = "Console.Out";

            consoleAppender.ActivateOptions();

            // A slight bit of hackery in order to programatically set more than one appender (which isn't supported by BasicConfigurator)
            log4net.Repository.Hierarchy.Logger root = ((log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository()).Root;
            root.AddAppender(consoleAppender);
            root.Repository.Configured = true;
        }
Ejemplo n.º 31
0
        private static void Init()
        {
            var hierarchy = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();

            hierarchy.Configured = true;

            var rollingAppender = new log4net.Appender.RollingFileAppender()
            {
                File         = LogConsts.FILE_PATH + @"\Log\log.log",
                AppendToFile = true,
                RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date,
                LockingModel = new log4net.Appender.FileAppender.MinimalLock(),
                DatePattern  = "_yyyyMMdd\".log\""
            };
            var layout = new log4net.Layout.PatternLayout("%date [%property{buildversion}] %-5level %logger - %message%newline");

            rollingAppender.Layout = layout;

            hierarchy.Root.AddAppender(rollingAppender);
            rollingAppender.ActivateOptions();

            hierarchy.Root.Level = log4net.Core.Level.All;
        }
Ejemplo n.º 32
0
        public static void InitializeLog4Net()
        {
            var layout = new log4net.Layout.PatternLayout()
            {
                ConversionPattern = "时间:%d %n级别:%level %n类名:%c%n文件:%F 第%L行%n日志内容:%m%n-----------------------------------------%n%n"
            };
            var appender = new log4net.Appender.RollingFileAppender()
            {
                AppendToFile      = true,
                LockingModel      = new log4net.Appender.FileAppender.MinimalLock(),
                StaticLogFileName = false,
                File         = System.Configuration.ConfigurationManager.AppSettings["LogFolder"] + "log_PingAn_",
                RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date,
                DatePattern  = "yyyy-MM-dd\".log\"",
                Layout       = layout
            };

            layout.ActivateOptions();
            appender.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(appender);

            //log4net.Config.XmlConfigurator.Configure();
        }
Ejemplo n.º 33
0
        private ILog CreateConflictLogger()
        {
            log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
            appender.AppendToFile       = true;
            appender.File               = Utils.GetConflictLogFileName();
            appender.ImmediateFlush     = true;
            appender.LockingModel       = new log4net.Appender.FileAppender.MinimalLock();
            appender.RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Size;
            appender.MaxFileSize        = 10 * 1024 * 1024;
            appender.MaxSizeRollBackups = 2;

            ///layout
            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("%date [%02thread] %-5level %message%newline");

            appender.Layout = layout;
            appender.ActivateOptions();
            log4net.Repository.ILoggerRepository repository = log4net.LogManager.CreateRepository("ConflictRepository");

            log4net.Config.BasicConfigurator.Configure(repository, appender);
            ILog logger = log4net.LogManager.GetLogger(repository.Name, "ConflictLog");

            return(logger);
        }
Ejemplo n.º 34
0
 /// <summary>
 /// 静态构造函数
 /// </summary>
 static LogHelper()
 {
     string path = string.Format("{0}log4net.config", AppDomain.CurrentDomain.BaseDirectory);
     if (File.Exists(path))
     {
         log4net.Config.XmlConfigurator.Configure(new FileInfo(path));
     }
     else
     {
         RollingFileAppender appender = new RollingFileAppender();
         appender.Name = "root";
         appender.File = "App_Data\\";
         appender.AppendToFile = true;
         appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
         appender.DatePattern = "yyyyMMdd-HHmm\".txt\"";
         appender.MaximumFileSize = "2MB";
         appender.MaxSizeRollBackups = 10;
         log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("%d{yyyy-MM-dd HH:mm:ss,fff}[%t] %-5p [%c] : %m%n");
         appender.Layout = layout;
         BasicConfigurator.Configure(appender);
         appender.ActivateOptions();
     }
 }
Ejemplo n.º 35
0
        public static void InitializeLog4Net()
        {
            var layout = new log4net.Layout.PatternLayout()
                {
                    ConversionPattern = "时间:%d %n级别:%level %n类名:%c%n文件:%F 第%L行%n日志内容:%m%n-----------------------------------------%n%n"
                };
            var appender = new log4net.Appender.RollingFileAppender()
            {
                AppendToFile = true,
                LockingModel = new log4net.Appender.FileAppender.MinimalLock(),
                StaticLogFileName = false,
                File = System.Configuration.ConfigurationManager.AppSettings["LogFolder"] + "log_PingAn_",
                RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date,
                DatePattern = "yyyy-MM-dd\".log\"",
                Layout = layout

            };
            layout.ActivateOptions();
            appender.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(appender);

            //log4net.Config.XmlConfigurator.Configure();
        }
Ejemplo n.º 36
0
        /// <summary>
        /// 创建高级Appender
        /// ERROR、FATAL两个级别的输出
        /// </summary>
        /// <returns></returns>
        private static IAppender CreateFileAppender()
        {
            log4net.Filter.LevelRangeFilter levfilter = new log4net.Filter.LevelRangeFilter();
            levfilter.LevelMax = log4net.Core.Level.Fatal;
            levfilter.LevelMin = log4net.Core.Level.Error;
            levfilter.ActivateOptions();
            RollingFileAppender appender = new RollingFileAppender();

            appender.AddFilter(levfilter);
            appender.Name              = "errorAppender";
            appender.File              = "SDK_Logs//Error//";
            appender.AppendToFile      = true;
            appender.RollingStyle      = RollingFileAppender.RollingMode.Date;
            appender.DatePattern       = "yyyy-MM-dd\".txt\"";
            appender.StaticLogFileName = false;
            appender.LockingModel      = new FileAppender.MinimalLock();
            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout();
            layout.ConversionPattern = "【日志级别】%-5level %n【记录时间】%date{HH:mm:ss,fff}  %n【描    述】%message %n %n";
            layout.ActivateOptions();
            appender.Layout = layout;
            appender.ActivateOptions();
            return(appender);
        }
Ejemplo n.º 37
0
        public static XMightLogger GerLoggerForName(String pName, String pHeader = null)
        {
            ILog logger = log4net.LogManager.GetLogger(pName);

            log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)logger.Logger;
            l.RemoveAllAppenders();

            DateFolderRollingFileAppender app1 = new DateFolderRollingFileAppender();

            app1.Name = pName + "Appender";
            app1.File = "logs\\" + pName;
            app1.PreserveLogFileNameExtension = true;
            app1.DatePattern       = ".dd-MM-yyyy";
            app1.AppendToFile      = false;
            app1.ImmediateFlush    = true;
            app1.RollingStyle      = log4net.Appender.RollingFileAppender.RollingMode.Date;
            app1.StaticLogFileName = false;

            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout();
            layout.ConversionPattern = "%d{dd-MM-yyyy HH:mm:ss.fff}\t%timestamp\t%message%newline";

            if (!String.IsNullOrEmpty(pHeader))
            {
                layout.Header = pHeader + "\n";
            }

            layout.ActivateOptions();

            app1.Layout = layout;
            app1.ActivateOptions();

            l.AddAppender(app1);
            l.Additivity = false;
            l.Level      = log4net.Core.Level.Debug;

            return(new XMightLogger(logger));
        }
        public CustomFormatterTest()
        {
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // Step 1. Create repository object
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            // Step 2. Create appender
            var splunkHttpEventCollector = new SplunkHttpEventCollector
            {
                SourceType = "json"
            };

            // Step 3. Set appender properties
            splunkHttpEventCollector.ServerUrl      = "https://localhost:8088";
            splunkHttpEventCollector.Token          = "ED9F5A37-BE9A-4782-B5F7-B6E31AC369CA";
            splunkHttpEventCollector.RetriesOnError = 0;

            log4net.Layout.PatternLayout patternLayout = new log4net.Layout.PatternLayout
            {
                ConversionPattern = "%message"
            };
            patternLayout.ActivateOptions();

            splunkHttpEventCollector.Layout = patternLayout;

            splunkHttpEventCollector.ActivateOptions(Formatter);

            // Step 4. Add appender to logger
            hierarchy.Root.AddAppender(splunkHttpEventCollector);
            hierarchy.Threshold  = Level.All;
            hierarchy.Configured = true;

            // Step 5. Create logger
            _logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        }
Ejemplo n.º 39
0
        static log4net.Appender.RollingFileAppender GetFileAppender(string name, log4net.Core.Level max, log4net.Core.Level min)
        {
            //设置过滤器
            log4net.Filter.LevelRangeFilter _levfilter = new log4net.Filter.LevelRangeFilter();
            _levfilter.LevelMax = max;
            _levfilter.LevelMin = min;
            _levfilter.ActivateOptions();

            //设计记录格式
            log4net.Layout.PatternLayout _layout = new log4net.Layout.PatternLayout("%date [%thread] %-5level - %message%newline");

            //Appender1
            log4net.Appender.RollingFileAppender _appender = new log4net.Appender.RollingFileAppender();
            //设置本Appander的名称
            _appender.Name = m_initTime.ToString("HHmmss") + "." + name + ".Appender";
            _appender.File = GetLogSavePath() + name + ".log";
            //否追加到文件
            _appender.AppendToFile       = true;
            _appender.MaxSizeRollBackups = 10;
            //日志文件名是否为静态
            _appender.StaticLogFileName = true;
            //_appender.DatePattern = "";
            //表示是否立即输出到文件,布尔型的。
            //_appender.ImmediateFlush
            //SecurityContext : 比较少应用,对日志进行加密只类的,使用SecurityContextProvider转换。(对日志的保密要求比较高的时候应该可以应用上吧,Log4考虑的还挺周全)
            //LockingModel : 文件锁类型,RollingFileAppender本身不是线程安全的,如果在程序中没有进行线程安全的限制,可以在这里进行配置,确保写入时的安全。有两中类型:FileAppender.ExclusiveLock 和 FileAppender.MinimalLock

            _appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date;
            //_appender.LockingModel = new log4net.Appender.FileAppender.MinimalLock();

            _appender.Layout = _layout;
            _appender.AddFilter(_levfilter);
            _appender.ActivateOptions();

            return(_appender);
        }
Ejemplo n.º 40
0
        private static void InitLog4netCfg(Level level)
        {
            log4net.Repository.Hierarchy.Hierarchy h = (log4net.Repository.Hierarchy.Hierarchy)LogManager.CreateRepository("Rep_" + AppContext.Instance.AppName);

            log4net.Appender.RollingFileAppender appender1 = new log4net.Appender.RollingFileAppender
            {
                Name               = "App_File_" + AppContext.Instance.AppName,
                AppendToFile       = true,
                File               = string.Format("LogFiles/"),
                ImmediateFlush     = true,
                MaxSizeRollBackups = 90,
                StaticLogFileName  = false,
                DatePattern        = "yyyyMMdd'.log'",
                RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Date
            };

            log4net.Layout.PatternLayout lay = new log4net.Layout.PatternLayout
            {
                //%d [%t] %-5p %c  - %m%n
                ConversionPattern = "%d %-5p - %m%n"
            };
            lay.ActivateOptions();
            appender1.Layout = lay;

            appender1.Encoding = Encoding.UTF8;

            appender1.ActivateOptions();

            h.Root.Level = level;

            h.Root.AddAppender(appender1);

            h.Configured = true;

            log4net.Config.BasicConfigurator.Configure(appender1);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// 静态构造函数
        /// </summary>
        static Log4NetUtil()
        {
            string path = string.Format("{0}Log4Net\\log4net.config", AppDomain.CurrentDomain.BaseDirectory);

            if (File.Exists(path))
            {
                log4net.Config.XmlConfigurator.Configure(new FileInfo(path));
            }
            else
            {
                RollingFileAppender appender = new RollingFileAppender();
                appender.Name               = "root";
                appender.File               = "Log/logs.txt";
                appender.AppendToFile       = true;
                appender.RollingStyle       = RollingFileAppender.RollingMode.Composite;
                appender.DatePattern        = "logs_yyyyMMdd\".txt\"";
                appender.MaximumFileSize    = "10MB";
                appender.MaxSizeRollBackups = 10;
                log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("%d{yyyy-MM-dd HH:mm:ss,fff}[%t] %-5p [%c] : %m%n");
                appender.Layout = layout;
                BasicConfigurator.Configure(appender);
                appender.ActivateOptions();
            }
        }
Ejemplo n.º 42
0
        public void SetConfigLogger(string pLogFileName)
        {
            m_Logger = log4net.LogManager.GetLogger(string.Format("{0}", pLogFileName));

            #region 로그 설정
            log4net.Repository.Hierarchy.Hierarchy hierarchy = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository();
            hierarchy.Configured = true;

            log4net.Appender.RollingFileAppender rollingAppender = new log4net.Appender.RollingFileAppender();
            rollingAppender.File              = string.Format(@"{0}\LOG\{1}", Application.StartupPath, pLogFileName); // 전체 경로에 생성할 메인 로그 파일 이름
            rollingAppender.AppendToFile      = true;
            rollingAppender.RollingStyle      = log4net.Appender.RollingFileAppender.RollingMode.Date;
            rollingAppender.LockingModel      = new log4net.Appender.FileAppender.MinimalLock();
            rollingAppender.StaticLogFileName = false;
            rollingAppender.DatePattern       = "_yyyy-MM-dd\".log\""; // 날짜가 지나간 경우 이전 로그에 붙을 이름 구성
            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("[%d]%n[Type : %p]%nMessage : %m%n%n");
            rollingAppender.Layout = layout;

            hierarchy.Root.AddAppender(rollingAppender);
            rollingAppender.ActivateOptions();

            hierarchy.Root.Level = log4net.Core.Level.All;
            #endregion
        }
Ejemplo n.º 43
0
        /// <summary>
        /// This method is used to create the appender
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="appenderName"></param>
        /// <returns></returns>
        private log4net.Appender.FileAppender CreateAppender(string fileName, string appenderName)
        {
            //log4net.Appender.FileAppender fileAppender = new log4net.Appender.FileAppender();
            log4net.Appender.RollingFileAppender fileAppender = new log4net.Appender.RollingFileAppender();

            log4net.Layout.PatternLayout patternLayOut = new log4net.Layout.PatternLayout();
            patternLayOut.Header = ""; //System.Environment.NewLine + "---Starts Here---" + System.Environment.NewLine;
            patternLayOut.Footer = ""; //
            patternLayOut.ConversionPattern = "%d %m%n";

            //patternLayOut.ConversionPattern = "";
            patternLayOut.ActivateOptions();

            string path = AppDomain.CurrentDomain.BaseDirectory + @"\Log" ;
            System.IO.DirectoryInfo info = new DirectoryInfo(path);

            if (!info.Exists)
            {
                info.Create();
            }
            string[] file = fileName.Split('\\');

            fileAppender.Layout = patternLayOut;

            fileAppender.AppendToFile = true;
            fileAppender.MaximumFileSize = Parameter.LOGGING_FILE_SIZE.Trim().Equals("") ? DefaultMaximumFileSize : Parameter.LOGGING_FILE_SIZE;

            fileAppender.MaxSizeRollBackups = 10;
            fileAppender.StaticLogFileName = true;
            fileAppender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Size;

            //fileAppender.File = path + "\\" + file[file.Length - 1];
            fileAppender.File = path + "\\" + fileName;
            fileAppender.Name = appenderName;

            fileAppender.LockingModel = new log4net.Appender.FileAppender.MinimalLock();
            fileAppender.ActivateOptions();

            return fileAppender;
        }
Ejemplo n.º 44
0
        private static void ReconfigureLog()
        {
            var hier = log4net.LogManager.GetRepository() as Hierarchy;
            if (hier != null)
            {
                // Get appender
                var jungoAppender = (RollingFileAppender)hier.GetAppenders()
                    .FirstOrDefault(
                        appender => appender.Name.Equals("JungoAppender", StringComparison.InvariantCultureIgnoreCase));

                if (jungoAppender != null)
                {
                    var config = ConfigLoader.Get<JungoLoggerLog4NetConfig>();
                    _configuredDelimiter = config.Delimiter;
                    _logLevelsIncluded = config.LogLevelsIncluded;
                    var delimiter = _configuredDelimiter == JungoLoggerLog4NetDelimiter.Comma ? "," : "\t";
                    var header = new StringBuilder("datetime");
                    var logFormatBuilder = new StringBuilder("{0}");
                    foreach (var column in config.Columns)
                    {
                        var colNum = -1;
                        switch (column.FieldName)
                        {
                            case "Order":                       colNum = 1; break;
                            case "LogType":                     colNum = 2; break;
                            case "RequestType":                 colNum = 3; break;
                            case "TimeElapsed":                 colNum = 4; break; 
                            case "Host":                        colNum = 5; break;
                            case "Uri":                         colNum = 6; break;
                            case "RequestPayload":              colNum = 7; break;
                            case "HttpStatus":                  colNum = 8; break;
                            case "DataFlow":                    colNum = 9; break;
                            case "ResponsePayload":             colNum = 10; break;
                            case "Error":                       colNum = 11; break;
                            case "SessionId":                   colNum = 12; break;
                            case "RequestId":                   colNum = 13; break;
                            case "DrRequestId":                 colNum = 14; break;
                            case "ResponsePayloadFirst1000":    colNum = 15; break;
                            case "ResponsePayloadCompressed":   colNum = 16; break;
                            case "ServerTrace":                 colNum = 17; break;
                        }
                        if (colNum < 0) continue;
                        header.Append(String.Format("{0}{1}", delimiter, column.Heading));
                        logFormatBuilder.Append(String.Format("{0}{{{1}}}", delimiter, colNum));
                    }
                    header.Append("\n\r");
                    if (config.Columns.Count() < 17)
                    {
                        for (var i = config.Columns.Count(); i < 17; i++)
                            logFormatBuilder.Append(delimiter);
                    }
                    _logFormat = logFormatBuilder.ToString();
                    var layout = new log4net.Layout.PatternLayout
                    {
                        Header = header.ToString(),
                        ConversionPattern = "%message%newline"
                    };
                    layout.ActivateOptions();
                    jungoAppender.Layout = layout;
                    jungoAppender.ActivateOptions();
                }
            }
            _log = log4net.LogManager.GetLogger("JungoLogger");
        }
Ejemplo n.º 45
0
        public static void SeparateOut(Type type)
        {
            if (type == null || separatedLoggers.ContainsKey(type))
            {
                return;
            }

            ILoggerRepository repository = LogManager.GetRepository();

            if (repository == null)
            {
                return;
            }

            IEnumerable <AppenderSkeleton> appenders = repository.GetAppenders().OfType <AppenderSkeleton>();

            if (appenders == null)
            {
                return;
            }

            ILog iLog = LogManager.GetLogger(type);

            separatedLoggers.Add(type, iLog);

            log4net.Filter.LoggerMatchFilter filter = new log4net.Filter.LoggerMatchFilter(),
                                             defaultLoggerFilter = new log4net.Filter.LoggerMatchFilter();
            filter.LoggerToMatch = iLog.Logger.Name;
            defaultLoggerFilter.AcceptOnMatch = filter.AcceptOnMatch = true;

            defaultLoggerFilter.LoggerToMatch = logger.Logger.Name;

            foreach (AppenderSkeleton appender in appenders)
            {
                List <log4net.Filter.IFilter> filters = new List <log4net.Filter.IFilter>();

                log4net.Filter.IFilter current = appender.FilterHead;

                if (current != null)
                {
                    filters.Add(current);
                    while ((current = current.Next) != null)
                    {
                        filters.Add(current);
                    }
                }

                appender.ClearFilters();
                appender.AddFilter(defaultLoggerFilter);

                foreach (log4net.Filter.IFilter f in filters)
                {
                    appender.AddFilter(f);
                }
            }

            RollingFileAppender separateAppender = new RollingFileAppender();

            separateAppender.File = Path.Combine(
                GlobalContext.Properties[Constants.Configuration.Logging.PATH_PROPERTY_NAME].ToNullSafeString(),
                type.FullName.Replace("+", "_") + ".log");
            separateAppender.AppendToFile       = true;
            separateAppender.SecurityContext    = log4net.Core.SecurityContextProvider.DefaultProvider.CreateSecurityContext(separateAppender);
            separateAppender.RollingStyle       = RollingFileAppender.RollingMode.Size;
            separateAppender.DatePattern        = ".yyyyMMdd";
            separateAppender.CountDirection     = 1;
            separateAppender.MaxSizeRollBackups = 7;
            separateAppender.MaximumFileSize    = "4MB";
            separateAppender.AddFilter(filter);
            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout();
            layout.Header            = "Date|Host|Environment|Thread|Level|Message\r\n";
            layout.ConversionPattern = "%date|%property{log4net:HostName}|%2thread|%-5level|%message%newline";
            separateAppender.Layout  = layout;
            log4net.Repository.Hierarchy.Hierarchy hierarchy = repository as log4net.Repository.Hierarchy.Hierarchy;
            hierarchy.Root.AddAppender(separateAppender);
            hierarchy.RaiseConfigurationChanged(EventArgs.Empty);
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Adds the email logging appender.
        /// </summary>
        public static void ConfigureEmailLoggingAppender()
        {
            var hier =
            (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();

            if (hier == null) return;

            var appender = (SmtpAppender)hier.Root.GetAppender("SmtpAppender") ?? new SmtpAppender();

            appender.Name = "SmtpAppender";
            appender.From = HostSettingManager.Get(HostSettingNames.HostEmailAddress, string.Empty);
            appender.To = HostSettingManager.Get(HostSettingNames.ErrorLoggingEmailAddress, string.Empty);
            appender.Subject = "BugNET Error";
            appender.SmtpHost = HostSettingManager.SmtpServer;
            appender.Port = int.Parse(HostSettingManager.Get(HostSettingNames.SMTPPort));
            appender.Authentication = SmtpAppender.SmtpAuthentication.None;
            appender.Username = string.Empty;
            appender.Password = string.Empty;
            appender.EnableSsl = Boolean.Parse(HostSettingManager.Get(HostSettingNames.SMTPUseSSL));

            if (Convert.ToBoolean(HostSettingManager.Get(HostSettingNames.SMTPAuthentication)))
            {
                appender.Authentication = SmtpAppender.SmtpAuthentication.Basic;
                appender.Username = String.Format("{0}\\{1}", HostSettingManager.Get(HostSettingNames.SMTPDomain, string.Empty), HostSettingManager.Get(HostSettingNames.SMTPUsername, string.Empty));
                appender.Password = HostSettingManager.Get(HostSettingNames.SMTPPassword, string.Empty);
            }

            appender.Priority = System.Net.Mail.MailPriority.High;
            appender.Threshold = log4net.Core.Level.Error;
            appender.BufferSize = 0;

            //create patternlayout
            var patternLayout = new
                log4net.Layout.PatternLayout("%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline");

            patternLayout.ActivateOptions();
            appender.Layout = patternLayout;
            appender.ActivateOptions();

            //add appender to root logger
            hier.Root.AddAppender(appender);
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Configures the logging object to use a console logger. This would normally be used
        /// as a fallback when either the application does not have any logging configuration
        /// or there is an error in it.
        /// </summary>
        public static void ConfigureConsoleLogger()
        {
            log4net.Appender.ConsoleAppender appender = new log4net.Appender.ConsoleAppender();

            log4net.Layout.ILayout fallbackLayout = new log4net.Layout.PatternLayout("%m%n");
            appender.Layout = fallbackLayout;

            log4net.Config.BasicConfigurator.Configure(appender);
        }
Ejemplo n.º 48
0
        /// <summary>
        /// add rolling file appender
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="patternStr"></param>
        public static void AddFileLogger(String filename, String patternStr)
        {
            if (!String.IsNullOrEmpty(filename))
            {
                if (String.IsNullOrEmpty(patternStr))
                    patternStr = "%message%newline";

                log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(patternStr);

                log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
                appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date;
                appender.Layout = layout;
                appender.File = filename;
                appender.DatePattern = "\"_\"yyyyMMdd\".txt\"";
                appender.StaticLogFileName = false;
                appender.ActivateOptions();

                m_Appenders.Add(appender);
            }
        }
Ejemplo n.º 49
0
        /// <summary>
        /// add console appender
        /// </summary>
        /// <param name="patternStr"></param>
        public static void AddConsoleLogger(String patternStr)
        {
            if (String.IsNullOrEmpty(patternStr))
                patternStr = "%message%newline";

            log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(patternStr);
            log4net.Appender.ConsoleAppender appender = new log4net.Appender.ConsoleAppender();

            appender.Layout = layout;
            m_Appenders.Add(appender);
        }
Ejemplo n.º 50
0
		public ILogger GetLogger(string name)
		{
			if(String.IsNullOrEmpty(name))
			{
				throw new ArgumentNullOrEmptyException("name");
			}

			if (RunContext.Current.RunMode == RunMode.Demo)
			{
				name = name + "_demo";
			}

			this.lock4loggers.EnterReadLock();
			try
			{
				if (this.loggers.ContainsKey(name))
				{
					return this.loggers[name];
				}
			}
			finally
			{
				this.lock4loggers.ExitReadLock();
			}

			this.lock4loggers.EnterWriteLock();
			try
			{
				if (this.loggers.ContainsKey(name))
				{
					return this.loggers[name];
				}

				// 当在默认日志配置文件 Repository 中未配置日志时,使用代码的方式对日志进行默认配置,配置后日志输出到 logs\{name}\n.log 中
				log4net.Core.ILogger logger = Repository.Exists(name);
				if (logger == null)
				{
					// 使用代码进行配置
					log4net.Repository.ILoggerRepository defaultRepository = CustomLogManager.GetRepository("defaultRepository_" + name);

					if (defaultRepository == null)
					{
						defaultRepository = CustomLogManager.CreateRepository("defaultRepository_" + name);

						defaultRepository.Threshold = log4net.Core.Level.Info;

						CustomFileAppender appender = new CustomFileAppender();
						appender.Name = name + "_Appender";
						appender.File = String.Format("logs\\{0}\\{1}.log", name, name);
						appender.Enable = true;
						appender.DirectoryByDate = true;
						appender.MaximumFileSize = "1000KB";
						appender.LockingModel = new log4net.Appender.FileAppender.ExclusiveLock();

						log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout();
						layout.ConversionPattern = "%date{MM-dd HH:mm:ss.fff} %-5level %-8property{RunMode} %-8property{Category} - %message%newline";
						layout.ActivateOptions();

						appender.Layout = layout;
						appender.Encoding = Encoding.UTF8;

						appender.ActivateOptions();

						log4net.Config.BasicConfigurator.Configure(defaultRepository, appender);
					}

					this.loggers[name] = new DefaultLogger(CustomLogManager.GetLogger(defaultRepository, name));

					return this.loggers[name];
				}
				else
				{
					this.loggers[name] = new DefaultLogger(CustomLogManager.GetLogger(Repository, name));

					return this.loggers[name];
				}
			}
			finally
			{
				this.lock4loggers.ExitWriteLock();
			}
		}
Ejemplo n.º 51
0
		void StartLogging()
		{
			//Setup log4net for the current domain
			log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
			log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("%date [%thread] %-5level %logger - %message%newline");
			appender.Layout = layout;
			appender.File = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"log\servicebrowser.log");
			appender.AppendToFile = true;
			appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date;
			appender.DatePattern = "yyyyMMdd";
			layout.ActivateOptions();
			appender.ActivateOptions();
			log4net.Config.BasicConfigurator.Configure(appender);
		}
Ejemplo n.º 52
0
 private static void ConfigureLogDefaults( string logfile )
 {
     log4net.Repository.Hierarchy.Hierarchy hierarchy = log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy;
     log4net.Layout.ILayout layout = new log4net.Layout.PatternLayout( "%-5p [%d{ISO8601}] %-20.20c{1} %m%n" );
     RollingFileAppender rfa = new RollingFileAppender();
     rfa.Layout = layout;
     rfa.File = logfile;
     rfa.AppendToFile = false;
     rfa.MaximumFileSize = "50MB";
     rfa.MaxSizeRollBackups = 3;
     rfa.Threshold = log4net.Core.Level.Debug;
     rfa.ActivateOptions();
     // hierarchy.Root.AddAppender(rfa);
     BasicConfigurator.Configure( rfa );
     ConsoleAppender ca = new ConsoleAppender();
     ca.Layout = layout;
     ca.Target = "Console.Out";
     ca.Threshold = log4net.Core.Level.Warn;
     ca.ActivateOptions();
     hierarchy.Root.AddAppender( ca );
 }
Ejemplo n.º 53
0
 public AzureAppender()
 {
     ScheduledTransferPeriod = GetScheduledTransferPeriod();
     Layout = new log4net.Layout.PatternLayout(GetLayout());
     Level = GetLevel();
 }
 /// <summary>
 /// Creates a layout object for a Db appender parameter
 /// </summary>
 /// <param name="LayoutStr">Name of parameter</param>
 /// <returns></returns>
 private static log4net.Layout.IRawLayout CreateLayout(string LayoutStr)
 {
     var layoutConvert = new log4net.Layout.RawLayoutConverter();
     var returnLayout = new log4net.Layout.PatternLayout
     {
         ConversionPattern = LayoutStr
     };
     returnLayout.ActivateOptions();
     var retItem = (log4net.Layout.IRawLayout)layoutConvert.ConvertFrom(returnLayout);
     return retItem;
 }
Ejemplo n.º 55
0
 public AzureAppender()
 {
     ScheduledTransferPeriod = GetScheduledTransferPeriod();
     Layout = new log4net.Layout.PatternLayout(GetLayout());
     Level  = GetLevel();
 }
Ejemplo n.º 56
0
        // Constructors
        public Log4netLoggerFactory(string configFilename = null)
        {
            // Setting
            log4net.MDC.Set("tab", "\t");

            // ConfigFileList
            List <FileInfo> configFileList = new List <FileInfo>();

            if (string.IsNullOrEmpty(configFilename) == false)
            {
                // GetAll
                configFileList = FileHelper.GetAllFile(configFilename);
                if (configFileList == null)
                {
                    throw new InvalidOperationException("configFileList=null");
                }
            }

            // Configure
            if (configFileList.Count > 0)
            {
                // Repository
                var repository = LogManager.GetRepository(System.Reflection.Assembly.GetEntryAssembly());
                if (repository == null)
                {
                    throw new InvalidOperationException("repository=null");
                }

                // XmlConfigurator
                foreach (var configFile in configFileList)
                {
                    XmlConfigurator.Configure(repository, configFile);
                }
            }
            else
            {
                // Repository
                var repository = LogManager.GetRepository(System.Reflection.Assembly.GetEntryAssembly());
                if (repository == null)
                {
                    throw new InvalidOperationException("repository=null");
                }

                // PatternLayout
                var patternLayout = new log4net.Layout.PatternLayout()
                {
                    ConversionPattern = @"%date{yyyy-MM-dd HH:mm:ss fff} %-5level [%thread] %logger.%property{method}() - %message%newline"
                };
                patternLayout.ActivateOptions();

                // ConsoleAppender
                var consoleAppender = new log4net.Appender.ConsoleAppender()
                {
                    Layout = patternLayout
                };
                consoleAppender.ActivateOptions();

                // FileAppender
                var fileAppender = new log4net.Appender.RollingFileAppender()
                {
                    Layout            = patternLayout,
                    RollingStyle      = RollingMode.Date,
                    File              = string.Format("log/{0}", System.Reflection.Assembly.GetEntryAssembly().GetName().Name),
                    DatePattern       = " yyyy-MM-dd'.log'",
                    StaticLogFileName = false,
                    AppendToFile      = true
                };
                fileAppender.ActivateOptions();

                // BasicConfigurator
                BasicConfigurator.Configure(repository,
                                            consoleAppender,
                                            fileAppender
                                            );
            }
        }
Ejemplo n.º 57
0
        /// <summary>
        /// intialize file writer
        /// </summary>
        /// <param name="_Filename"></param>
        void InitializeBackupFile(String _Filename)
        {
            try
            {
                if (!String.IsNullOrEmpty(_Filename) && null == m_BackupAppender)
                {
                    String patternStr = "%date : %message%newline";

                    log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(patternStr);

                    log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
                    appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date;
                    appender.Layout = layout;
                    appender.File = _Filename;
                    appender.DatePattern = "\"_\"yyyyMMdd\".txt\"";
                    appender.StaticLogFileName = false;
                    appender.ActivateOptions();

                    m_BackupAppender = appender;
                }
            }
            catch (System.Exception ex)
            {
                m_BackupAppender = null;
                Log.Error("初始化备份文件失败.", ex);
            }
        }
Ejemplo n.º 58
0
        protected override void ProcessRecord()
        {
            //todo set default to scriptname.log
            string test = MyInvocation.ScriptName;

            log4net.ILog       logger      = log4net.LogManager.GetLogger("Powershell");
            System.IO.FileInfo logFileInfo = new System.IO.FileInfo(_logConfigFile);
            log4net.Config.XmlConfigurator.ConfigureAndWatch(logFileInfo);
            WriteObject(logger);

            log4net.Appender.IAppender[] appenders = log4net.LogManager.GetRepository().GetAppenders();
            foreach (log4net.Appender.IAppender logAppender in appenders)
            {
                #region RollingFilleAppender
                if ((logAppender.GetType() == typeof(log4net.Appender.RollingFileAppender)) && logAppender.Name == "OSCCDefaultRollingFileAppender")
                {
                    log4net.Appender.FileAppender fileAppender = (log4net.Appender.RollingFileAppender)logAppender;
                    if (MyInvocation.BoundParameters.ContainsKey("LogFileName"))
                    {
                        log4net.Util.PatternString dynamicFileName         = new log4net.Util.PatternString(LogFileName);
                        log4net.Util.ConverterInfo adminuiLogConverterInfo = new log4net.Util.ConverterInfo();
                        adminuiLogConverterInfo.Name = "adminuilog";
                        adminuiLogConverterInfo.Type = typeof(Log4Net_CMTrace.CMAdminUILogFolderPatternConverter);
                        log4net.Util.ConverterInfo ccmLogConverterInfo = new log4net.Util.ConverterInfo();
                        ccmLogConverterInfo.Name = "ccmlog";
                        ccmLogConverterInfo.Type = typeof(Log4Net_CMTrace.CMClientLogFolderPatternConverter);
                        log4net.Layout.PatternLayout newLayout = new log4net.Layout.PatternLayout();
                        dynamicFileName.AddConverter(adminuiLogConverterInfo);
                        dynamicFileName.AddConverter(ccmLogConverterInfo);
                        dynamicFileName.ActivateOptions();
                        //fileAppender.File = LogFileName;
                        fileAppender.File = dynamicFileName.Format();
                    }
                    else
                    {
                        if (MyInvocation.ScriptName != "")
                        {
                            fileAppender.File = MyInvocation.ScriptName + ".log";
                        }
                    }
                    if (MyInvocation.BoundParameters.ContainsKey("FileLogLevel"))
                    {
                        switch (FileLogLevel.ToLower())
                        {
                        case "off": fileAppender.Threshold = log4net.Core.Level.Off; break;

                        case "info": fileAppender.Threshold = log4net.Core.Level.Info; break;

                        case "warn": fileAppender.Threshold = log4net.Core.Level.Warn; break;

                        case "error": fileAppender.Threshold = log4net.Core.Level.Error; break;

                        case "debug": fileAppender.Threshold = log4net.Core.Level.Debug; break;

                        default: fileAppender.Threshold = log4net.Core.Level.Info; break;
                        }
                    }
                    else
                    {
                        fileAppender.Threshold = log4net.Core.Level.Info;
                    }
                    fileAppender.ActivateOptions();
                }
                #endregion

                #region OMSFilleAppender
                if ((logAppender.GetType() == typeof(log4net.Appender.FileAppender)) && logAppender.Name == "OSCCOMSFileAppender")
                {
                    log4net.Appender.FileAppender fileAppender = (log4net.Appender.FileAppender)logAppender;
                    if (MyInvocation.BoundParameters.ContainsKey("OMSLogFileName"))
                    {
                        log4net.Util.PatternString dynamicFileName         = new log4net.Util.PatternString(LogFileName);
                        log4net.Util.ConverterInfo adminuiLogConverterInfo = new log4net.Util.ConverterInfo();
                        adminuiLogConverterInfo.Name = "adminuilog";
                        adminuiLogConverterInfo.Type = typeof(Log4Net_CMTrace.CMAdminUILogFolderPatternConverter);
                        log4net.Util.ConverterInfo ccmLogConverterInfo = new log4net.Util.ConverterInfo();
                        ccmLogConverterInfo.Name = "ccmlog";
                        ccmLogConverterInfo.Type = typeof(Log4Net_CMTrace.CMClientLogFolderPatternConverter);
                        log4net.Layout.PatternLayout newLayout = new log4net.Layout.PatternLayout();
                        dynamicFileName.AddConverter(adminuiLogConverterInfo);
                        dynamicFileName.AddConverter(ccmLogConverterInfo);
                        dynamicFileName.ActivateOptions();
                        //fileAppender.File = LogFileName;
                        fileAppender.File = dynamicFileName.Format();
                    }
                    else
                    {
                        if (MyInvocation.ScriptName != "")
                        {
                            fileAppender.File = MyInvocation.ScriptName + ".OMS." + DateTime.Today.ToString("yyyyMMdd") + ".log";
                        }
                    }
                    if (MyInvocation.BoundParameters.ContainsKey("OMSFileLogLevel"))
                    {
                        switch (FileLogLevel.ToLower())
                        {
                        case "off": fileAppender.Threshold = log4net.Core.Level.Off; break;

                        case "info": fileAppender.Threshold = log4net.Core.Level.Info; break;

                        case "warn": fileAppender.Threshold = log4net.Core.Level.Warn; break;

                        case "error": fileAppender.Threshold = log4net.Core.Level.Error; break;

                        case "debug": fileAppender.Threshold = log4net.Core.Level.Debug; break;

                        default: fileAppender.Threshold = log4net.Core.Level.Info; break;
                        }
                    }
                    fileAppender.ActivateOptions();
                }
                #endregion
                #region ConsoleAppender
                if (logAppender.GetType() == typeof(log4net.Appender.ConsoleAppender))
                {
                    log4net.Appender.ConsoleAppender consoleAppender = (log4net.Appender.ConsoleAppender)logAppender;
                    if (this.Host.Name.ToLower() == "consolehost")
                    {
                        if (MultiColor == false)
                        {
                            {
                                if (MyInvocation.BoundParameters.ContainsKey("ConsoleLogLevel"))
                                {
                                    switch (ConsoleLogLevel.ToLower())
                                    {
                                    case "off": consoleAppender.Threshold = log4net.Core.Level.Off; break;

                                    case "info": consoleAppender.Threshold = log4net.Core.Level.Info; break;

                                    case "warn": consoleAppender.Threshold = log4net.Core.Level.Warn; break;

                                    case "error": consoleAppender.Threshold = log4net.Core.Level.Error; break;

                                    case "debug": consoleAppender.Threshold = log4net.Core.Level.Debug; break;

                                    default: consoleAppender.Threshold = log4net.Core.Level.Info; break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            consoleAppender.Threshold = log4net.Core.Level.Off;
                        }
                    }
                    else
                    {
                        if (this.Host.Name.ToLower() == "windows powershell ise host")
                        {
                            if (MyInvocation.BoundParameters.ContainsKey("ConsoleLogLevel"))
                            {
                                switch (ConsoleLogLevel.ToLower())
                                {
                                case "off": consoleAppender.Threshold = log4net.Core.Level.Off; break;

                                case "info": consoleAppender.Threshold = log4net.Core.Level.Info; break;

                                case "warn": consoleAppender.Threshold = log4net.Core.Level.Warn; break;

                                case "error": consoleAppender.Threshold = log4net.Core.Level.Error; break;

                                case "debug": consoleAppender.Threshold = log4net.Core.Level.Debug; break;

                                default: consoleAppender.Threshold = log4net.Core.Level.Info; break;
                                }
                            }
                            if ((MyInvocation.BoundParameters.ContainsKey("MultiColor")) && (MultiColor == true))
                            {
                                Console.WriteLine("Powershell ISe does not support multi colored displays.");
                            }
                        }
                    }
                    consoleAppender.ActivateOptions();
                }
                #endregion
                #region coloredconsoleappender
                if (logAppender.GetType() == typeof(log4net.Appender.ColoredConsoleAppender))
                {
                    log4net.Appender.ColoredConsoleAppender coloredConsoleAppender = (log4net.Appender.ColoredConsoleAppender)logAppender;
                    if (this.Host.Name.ToLower() == "consolehost")
                    {
                        if (MultiColor == true)
                        {
                            if (MyInvocation.BoundParameters.ContainsKey("ConsoleLogLevel"))
                            {
                                switch (ConsoleLogLevel.ToLower())
                                {
                                case "off": coloredConsoleAppender.Threshold = log4net.Core.Level.Off; break;

                                case "info": coloredConsoleAppender.Threshold = log4net.Core.Level.Info; break;

                                case "warn": coloredConsoleAppender.Threshold = log4net.Core.Level.Warn; break;

                                case "error": coloredConsoleAppender.Threshold = log4net.Core.Level.Error; break;

                                case "debug": coloredConsoleAppender.Threshold = log4net.Core.Level.Debug; break;

                                default: coloredConsoleAppender.Threshold = log4net.Core.Level.Info; break;
                                }
                            }
                        }
                        else
                        {
                            coloredConsoleAppender.Threshold = log4net.Core.Level.Off;
                        }
                    }
                    if (this.Host.Name.ToLower() == "windows powershell ise host")
                    {
                        coloredConsoleAppender.Threshold = log4net.Core.Level.Off;
                    }
                    coloredConsoleAppender.ActivateOptions();
                }
                #endregion
            }
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Initialisiert das Logging und die Debug TextBox
        /// </summary>
        private void InitLog()
        {
            #region RichTextBoxAppender
            RichTextBoxAppender rba = new RichTextBoxAppender(rtbDebug);
            rba.Threshold = Level.All;
            rba.Layout = new log4net.Layout.PatternLayout("%date{dd-MM-yyyy HH:mm:ss.fff} %5level %message %n");

            LevelTextStyle ilts = new LevelTextStyle();
            ilts.Level = Level.Info;
            ilts.TextColor = Color.DarkBlue;
            ilts.PointSize = 8.0f;
            rba.AddMapping(ilts);

            LevelTextStyle dlts = new LevelTextStyle();
            dlts.Level = Level.Debug;
            dlts.TextColor = Color.DeepSkyBlue;
            dlts.PointSize = 8.0f;
            rba.AddMapping(dlts);

            LevelTextStyle wlts = new LevelTextStyle();
            wlts.Level = Level.Warn;
            wlts.TextColor = Color.Gold;
            wlts.PointSize = 8.0f;
            rba.AddMapping(wlts);

            LevelTextStyle elts = new LevelTextStyle();
            elts.Level = Level.Error;
            elts.TextColor = Color.Crimson;
            elts.BackColor = Color.Cornsilk;
            elts.PointSize = 8.0f;
            rba.AddMapping(elts);

            LevelTextStyle flts = new LevelTextStyle();
            flts.Level = Level.Fatal;
            flts.TextColor = Color.White;
            flts.BackColor = Color.Red;
            flts.PointSize = 8.0f;
            rba.AddMapping(flts);

            log4net.Config.BasicConfigurator.Configure(rba);
            rba.ActivateOptions();
            #endregion RichTextBoxAppender

            #region RollingFileAppender
            log4net.Appender.RollingFileAppender fa = new log4net.Appender.RollingFileAppender();
            fa.AppendToFile = true;
            fa.Threshold = log4net.Core.Level.All;
            fa.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Date;
            fa.MaxFileSize = 100000;
            fa.MaxSizeRollBackups = 10;
            fa.File = @".\LogPath\K-S2-Remote_";
            fa.DatePattern = @"yyyyMMdd.lo\g";
            fa.StaticLogFileName = false;

            // fa.Layout = new log4net.Layout.PatternLayout("%date{dd-MM-yyyy HH:mm:ss.fff} %5level %message (%logger{1}:%line)%n");
            log4net.Layout.PatternLayout pl = new log4net.Layout.PatternLayout(
                "%date [%thread] %-5level %message    (%logger)%newline");
            pl.Header = "######### K-S2-Remote_ gestartet ############\n";
            pl.Footer = "######### K-S2-Remote_ gestoppt  ############\n";
            fa.Layout = pl;

            log4net.Config.BasicConfigurator.Configure(fa);
            fa.ActivateOptions();
            #endregion RollingFileAppender
        }