예제 #1
0
        public static void Configure()
        {
            var hierarchy = (Hierarchy)LogManager.GetRepository();
            hierarchy.Root.RemoveAllAppenders();

            // see http://logging.apache.org/log4net/release/sdk/log4net.Layout.PatternLayout.html

            var layout = new PatternLayout
            {
                ConversionPattern = "%date{dd-MMM-yyyy HH:mm:ss}  %-5level  %message%n%exception%n"
            };

            var fileAppender = new RollingFileAppender
            {
                Layout = layout,
                AppendToFile = true,
                File = "log.txt",
                LockingModel = new FileAppender.MinimalLock(),
            };

            var consoleAppender = new ConsoleAppender
            {
                Layout = layout,
            };

            layout.ActivateOptions();

            fileAppender.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(fileAppender);

            consoleAppender.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(consoleAppender);
        }
예제 #2
0
        public LogConfig()
        {
            rootLevel = log4net.Core.Level.Debug;

            patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%d %-7p [TID=%3t] %m%n";

            consoleAppender = new ManagedColoredConsoleAppender();
            consoleAppender.Layout = patternLayout;
            consoleAppender.AddMapping(new ManagedColoredConsoleAppender.LevelColors() { ForeColor = ConsoleColor.Red, BackColor=ConsoleColor.White, Level = log4net.Core.Level.Fatal });
            consoleAppender.AddMapping(new ManagedColoredConsoleAppender.LevelColors() { ForeColor = ConsoleColor.Red, Level = log4net.Core.Level.Error});
            consoleAppender.AddMapping(new ManagedColoredConsoleAppender.LevelColors() { ForeColor = ConsoleColor.Yellow, Level = log4net.Core.Level.Warn });
            consoleAppender.AddMapping(new ManagedColoredConsoleAppender.LevelColors() { ForeColor = ConsoleColor.Green, Level = log4net.Core.Level.Info});
            consoleAppender.AddMapping(new ManagedColoredConsoleAppender.LevelColors() { ForeColor = ConsoleColor.White, Level = log4net.Core.Level.Debug});
            consoleAppender.AddMapping(new ManagedColoredConsoleAppender.LevelColors() { ForeColor = ConsoleColor.Gray, Level = log4net.Core.Level.Verbose });

            rollingAppender = new RollingFileAppender();
            rollingAppender.Layout = patternLayout;
            rollingAppender.MaxFileSize = 10 * 1048576;
            rollingAppender.MaxSizeRollBackups = 20;
            rollingAppender.AppendToFile = true;
            rollingAppender.RollingStyle = RollingFileAppender.RollingMode.Size;
            rollingAppender.StaticLogFileName = true;
            rollingAppender.File = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Assembly.GetEntryAssembly().GetName().Name + ".log");
        }
예제 #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;
        }
예제 #4
0
        private RollingFileAppender CreateAppender(string appenderName, string fileName, ComonLog.LogLevel logLevel)
        {
            PatternLayout layout = new PatternLayout();
            layout.ConversionPattern = "%d %-5p  %m%n";
            layout.ActivateOptions();

            RollingFileAppender appender = new RollingFileAppender();
            appender.Layout = layout;

            appender.Name = appenderName;
            appender.File = fileName;

            appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
            //appender.Encoding = Encoding.Unicode;
            appender.AppendToFile = true;
            appender.MaximumFileSize = "4MB";
            appender.MaxSizeRollBackups = 100;
            appender.DatePattern = "yyyy-MM-dd";
            appender.PreserveLogFileNameExtension = true;
            appender.StaticLogFileName = false;
            appender.Threshold = FileAppenderHelper.ConvertLogLevel(logLevel);

            log4net.Filter.LevelRangeFilter levfilter = new log4net.Filter.LevelRangeFilter();
            levfilter.LevelMax = appender.Threshold;
            levfilter.LevelMin = appender.Threshold;
            levfilter.ActivateOptions();

            appender.AddFilter(levfilter);

            appender.ActivateOptions();

            return appender;
        }
        protected override void ConfigurePlugin(PluginConfiguration pluginConfiguration, PluginInspector pluginInspector)
        {
            _moduleName = pluginConfiguration.ModuleName;
            BasicConfigurator.Configure();

            var defaultPattern = new PatternLayout { ConversionPattern = LogPattern };
            defaultPattern.ActivateOptions();

            var rollingFileAppender = new RollingFileAppender
            {
                Name = "RollingFileAppender",
                File = "Log/" + _moduleName + ".log",
                AppendToFile = true,
                RollingStyle = RollingFileAppender.RollingMode.Size,
                MaxSizeRollBackups = 15,
                MaximumFileSize = "100MB",
                StaticLogFileName = true,
                Layout = defaultPattern
            };
            rollingFileAppender.ActivateOptions();
            rollingFileAppender.ImmediateFlush = true;
            rollingFileAppender.LockingModel= new FileAppender.InterProcessLock();

            var root = ((Hierarchy)global::log4net.LogManager.GetRepository()).Root;
            root.AddAppender(rollingFileAppender);
            root.Level = Level.Debug;
            root.Repository.Configured = true;
        }
 private void SetupLogger()
 {
     Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
     PatternLayout patternLayout = new PatternLayout();
     patternLayout.ConversionPattern = "%date [%thread] %-5level [%class.%method] - %message%newline";
     patternLayout.ActivateOptions();
     RollingFileAppender roller = new RollingFileAppender();
     roller.AppendToFile = false;
     roller.File = @"ResultExporterLog.txt";
     roller.Layout = patternLayout;
     roller.MaxSizeRollBackups = 5;
     roller.MaximumFileSize = "1GB";
     roller.RollingStyle = RollingFileAppender.RollingMode.Size;
     roller.StaticLogFileName = true;
     roller.ActivateOptions();
     ConsoleAppender console = new ConsoleAppender();
     PatternLayout consolePatternLayout = new PatternLayout();
     consolePatternLayout.ConversionPattern = "%date [Testlink Result Exporter] [%level] %message%newline";
     consolePatternLayout.ActivateOptions();
     LevelRangeFilter consoleLevelFilter = new LevelRangeFilter();
     consoleLevelFilter.LevelMin = Level.Info;
     consoleLevelFilter.LevelMax = Level.Fatal;
     console.AddFilter(consoleLevelFilter);
     console.Layout = consolePatternLayout;
     hierarchy.Root.AddAppender(roller);
     hierarchy.Root.AddAppender(console);
     hierarchy.Root.Level = Level.All;
     hierarchy.Configured = true;
 }
예제 #7
0
        /// <summary>
        /// Setups the logger configuration. Can be used instead of loading log4net.config file
        /// </summary>
        public static void SetupLogger()
        {
            Hierarchy hierarchy = (Hierarchy) LogManager.GetRepository();

            PatternLayout patternLayout = new DynamicPatternLayout();
            patternLayout.ConversionPattern = "%date{dd MMM yyyy HH:mm:ss} [%thread] %level   -   %message %exception %newline";
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender
                                             {
                                                 // appends the log into same file
                                                 AppendToFile = true,
                                                 File = @"DeployLogs\\Deploylog.log",
                                                 Layout = patternLayout,
                                                 MaxSizeRollBackups = 1000,
                                                 RollingStyle = RollingFileAppender.RollingMode.Date,
                                                 StaticLogFileName = false
                                             };

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

            MemoryAppender memoryAppender = new MemoryAppender();
            memoryAppender.ActivateOptions();

            hierarchy.Root.AddAppender(memoryAppender);

            hierarchy.Root.Level = Level.All;
            hierarchy.Configured = true;
        }
예제 #8
0
        /// <summary>
        /// configure method
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="repository">repository</param>
        public override void Configure(string key, ILoggerRepository repository)
        {
            var path = Path.Replace(":", "_");

            foreach (var level in Levels)
            {
                var appender = new log4net.Appender.RollingFileAppender();
                appender.File           = Folder + (string.IsNullOrEmpty(path) ? "" : path) + "/" + level.ToString().ToLower() + ".log";
                appender.AppendToFile   = true;
                appender.ImmediateFlush = true;
                appender.LockingModel   = new FileAppender.MinimalLock();
                appender.Threshold      = level;

                var layout = new PatternLayout(Pattern);
                layout.ActivateOptions();

                appender.Layout = layout;
                appender.Name   = key + "_" + level.ToString().ToLower();

                var filter = new LevelRangeFilter();
                filter.LevelMax = level;
                filter.LevelMin = level;
                filter.ActivateOptions();
                appender.AddFilter(filter);

                appender.ActivateOptions();

                BasicConfigurator.Configure(repository, appender);
            }
        }
예제 #9
0
파일: Bootstrap.cs 프로젝트: zhh007/CKGen
        private static void InitLog4net()
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "[%date] %-5level [%thread] %property{user} - %message%exception%n";
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();
            roller.AppendToFile = true;
            roller.File = @"logs\";
            roller.Layout = patternLayout;
            roller.MaxSizeRollBackups = 100;
            roller.MaximumFileSize = "10MB";
            roller.RollingStyle = RollingFileAppender.RollingMode.Date;
            roller.DatePattern = "yyyyMMdd'.log'";
            roller.StaticLogFileName = false;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

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

            log4net.GlobalContext.Properties["user"] = new Log4NetUserNameProvider();
        }
예제 #10
0
        static Logger()
        {
            var hierarchy = (Hierarchy)LogManager.GetRepository();
            var tracer = new TraceAppender();
            var patternLayout = new PatternLayout {ConversionPattern = LOG_PATTERN};

            patternLayout.ActivateOptions();

            tracer.Layout = patternLayout;
            tracer.ActivateOptions();
            hierarchy.Root.AddAppender(tracer);

            var roller = new RollingFileAppender
                             {
                                 Layout = patternLayout,
                                 AppendToFile = true,
                                 RollingStyle = RollingFileAppender.RollingMode.Size,
                                 MaxSizeRollBackups = 4,
                                 MaximumFileSize = "10240KB",
                                 StaticLogFileName = true,
                                 File = FilePath + @"\f1speed-log.txt"
                             };
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            hierarchy.Root.Level = Level.Debug;
            hierarchy.Configured = true;
        }
예제 #11
0
        public DefaultLogWrapper(string logname, IConfig config)
        {
            this.logname = logname;

            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
            hierarchy.Clear();

            TraceAppender tracer = new TraceAppender();
            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = "%t (%-5level) - %m%n";
            patternLayout.ActivateOptions();

            tracer.Layout = patternLayout;
            tracer.ActivateOptions();
            hierarchy.Root.AddAppender(tracer);

            RollingFileAppender roller = new RollingFileAppender();
            roller.Layout = patternLayout;
            roller.AppendToFile = true;
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.MaxSizeRollBackups = 4;
            roller.MaximumFileSize = "100KB";
            roller.StaticLogFileName = true;
            roller.File = Path.Combine(config.IndexFolder, "totalrecall-" + this.logname + ".log");
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            hierarchy.Root.Level = Level.All;
            hierarchy.Configured = true;
        }
예제 #12
0
        public void Setup()
        {
            var applicationDataDirectory =
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    "PCoMD", "Log");
            LogFilePath = Path.Combine(applicationDataDirectory, "PCoMD.xml");

            var hierarchy = (Hierarchy) LogManager.GetRepository();

            var patternLayout = new XmlLayoutSchemaLog4j();
            patternLayout.LocationInfo = true;
            patternLayout.ActivateOptions();

            var roller = new RollingFileAppender
            {
                AppendToFile = true,
                MaximumFileSize = "2MB",
                File = LogFilePath,
                PreserveLogFileNameExtension = true,
                MaxSizeRollBackups = 10,
                RollingStyle = RollingFileAppender.RollingMode.Size,
                Layout = patternLayout
            };
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            var memory = new MemoryAppender();
            memory.ActivateOptions();
            hierarchy.Root.AddAppender(memory);

            hierarchy.Root.Level = Level.Info;
            hierarchy.Configured = true;

            XmlConfigurator.Configure(hierarchy);
        }
예제 #13
0
파일: Log4net.cs 프로젝트: abayaz61/NCache
        /// <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 static log4net.Appender.IAppender CreateRollingFileAppender(string cacheName, string fileName)
        {
            log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
            appender.Name = "RollingFileAppender" + cacheName;
            appender.File = fileName;
            //doesnt matter since all files are created with a new name
            appender.AppendToFile = false;

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

            //Threshold is maintained by the logger rather than the appenders
            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 ||
            layout.ConversionPattern = "%-27date{ISO8601}" + "\t%-45.42appdomain" + "\t%-35logger" + "\t%-42thread" + "\t%-9level" + "\t%message" + "%newline";

            layout.Header = "TIMESTAMP                  \tAPPDOMAIN                                    \tLOGGERNAME                         \tTHREADNAME                                \tLEVEL    \tMESSAGE\r\n";
            layout.Footer = "END \n";

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

            return(appender);
        }
예제 #14
0
        static Logger()
        {
            const string filename = "log4net.config";
            string basePath = HttpContext.Current != null
                ? AppDomain.CurrentDomain.SetupInformation.PrivateBinPath
                : AppDomain.CurrentDomain.BaseDirectory;
            string configFile = Path.Combine(basePath, filename);
            if (File.Exists(configFile))
            {
                XmlConfigurator.ConfigureAndWatch(new FileInfo(configFile));
                return;
            }

            //默认设置
            RollingFileAppender appender = new RollingFileAppender
            {
                Name = "root",
                File = "logs\\log",
                AppendToFile = true,
                RollingStyle = RollingFileAppender.RollingMode.Composite,
                DatePattern = "yyyyMMdd\".log\"",
                MaxSizeRollBackups = 10
            };

            PatternLayout layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss.fff}] %c.%M %t %n%m%n");
            appender.Layout = layout;
            BasicConfigurator.Configure(appender);
            appender.ActivateOptions();
        }
예제 #15
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);
        }
예제 #16
0
        public static void Configure(string appfolder, string logFile)
        {
            bool isConfigured = _log.Logger.Repository.Configured;

            if (!isConfigured)
            {
                // Setup RollingFileAppender
                var fileAppender = new RollingFileAppender
                {
                    Layout =
                        new PatternLayout(
                        "%d %level [%type{1}] - %m%n"),
                    MaximumFileSize = "1000KB",
                    MaxSizeRollBackups = 10,
                    RollingStyle = RollingFileAppender.RollingMode.Composite,
                    AppendToFile = true,
                    File = logFile,
                    ImmediateFlush = true,
                    LockingModel = new FileAppender.MinimalLock(),
                    Name = "XXXRollingFileAppender",
                    Threshold = log4net.Core.Level.All
                };
                fileAppender.ActivateOptions(); // IMPORTANT, creates the file
                BasicConfigurator.Configure(fileAppender);
            #if DEBUG
                // Setup TraceAppender
                TraceAppender ta = new TraceAppender();
                ta.Layout = new PatternLayout("%d [%t]%-5p %c [%x] - %m%n");
                BasicConfigurator.Configure(ta);
            #endif
            }
        }
예제 #17
0
        public void SetPath(String path)
        {
            //_writer = new StreamWriter(path);

            //_path = path;
            PatternLayout patternLayout = new PatternLayout
            {
                ConversionPattern = "[%date] - [%logger] - %level  - %message%newline"
            };
            patternLayout.ActivateOptions();

            RollingFileAppender rollingFileAppender = new RollingFileAppender
            {
                File = path,
                Layout = patternLayout,
                MaximumFileSize = "5MB",
                MaxSizeRollBackups = 2,
                PreserveLogFileNameExtension = true,
                RollingStyle = RollingFileAppender.RollingMode.Size,
                LockingModel = new FileAppender.MinimalLock()
            };
            rollingFileAppender.ActivateOptions();

            Hierarchy hierarchy = LogManager.GetRepository() as Hierarchy;
            Logger root = hierarchy.Root;
            root.RemoveAllAppenders();

            root.Level = Level.All;

            BasicConfigurator.Configure(rollingFileAppender);
        }
예제 #18
0
        public void Init(ListView listView1)
        {
            string DirectoryName = "log";

            Directory.CreateDirectory(DirectoryName);


            ListViewAppender ListViewAppender1 = new ListViewAppender(listView1);

            ListViewAppender1.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(ListViewAppender1);

            log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
            appender.File              = DirectoryName + "\\";
            appender.AppendToFile      = true;
            appender.RollingStyle      = log4net.Appender.RollingFileAppender.RollingMode.Date;
            appender.DatePattern       = "yyyy-MM-dd\".txt\"";
            appender.Layout            = new log4net.Layout.PatternLayout("%date{HH:mm:ss}   %message%newline");
            appender.StaticLogFileName = false;
            appender.ImmediateFlush    = true;
            appender.LockingModel      = new log4net.Appender.FileAppender.MinimalLock();
            appender.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(appender);

            this.ILog = LogManager.GetLogger("Logger");
        }
예제 #19
0
        //public static void AddAppender(string appenderName, ILogger wLogger)
        //{
        //    log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)wLogger;

        //    log4net.Appender.IAppender hasAppender = l.GetAppender(appenderName);
        //    if (hasAppender != null)
        //    {
        //        hasAppender..ActivateOptions();

        //        l.AddAppender(hasAppender);
        //    }
        //}

        public static void AddAppender(string appenderName, ILogger wLogger)
        {
            string filename = ConfigurationManager.AppSettings["LogDir"].ToString() + "\\" + appenderName + ".log";

            log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)wLogger;

            log4net.Appender.IAppender hasAppender = l.GetAppender(appenderName);
            if (hasAppender == null)
            {
                log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();

                appender.DatePattern       = "yyyyMMdd";
                appender.RollingStyle      = log4net.Appender.RollingFileAppender.RollingMode.Date;
                appender.AppendToFile      = true;
                appender.File              = filename;
                appender.StaticLogFileName = true;
                appender.Name              = appenderName;

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

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


                l.AddAppender(appender);
            }
        }
예제 #20
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)
        {
            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();

            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";
            layout.Footer = "END \n";

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

            return(appender);
        }
예제 #21
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()];
        }
        public static void ConfigureLogging()
        {
            var layout = new PatternLayout
            {
                ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n"
            };
            layout.ActivateOptions();
            var consoleAppender = new ColoredConsoleAppender
            {
                Threshold = Level.Debug,
                Layout = layout
            };
            consoleAppender.ActivateOptions();
            var fileAppender = new RollingFileAppender
            {
                DatePattern = "yyyy-MM-dd'.txt'",
                MaxFileSize = 10 * 1024 * 1024,
                MaxSizeRollBackups = 10,
                StaticLogFileName = false,
                File = @"d:\logs\auth",
                Layout = layout,
                AppendToFile = true,
                Threshold = Level.Debug,
            };

            #if DEBUG
            fileAppender.File = @"log_";
            #endif

            fileAppender.ActivateOptions();

            BasicConfigurator.Configure(fileAppender, consoleAppender);
        }
        public static void Setup(string path)
        {
            var hierarchy = (Hierarchy)LogManager.GetRepository();

            var patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
            // patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
            patternLayout.ActivateOptions();

            var roller = new RollingFileAppender();
            roller.AppendToFile = true;
            roller.File = path;
            roller.Layout = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize = "2MB";
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName = true;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            var memory = new MemoryAppender();
            memory.ActivateOptions();
            hierarchy.Root.AddAppender(memory);

            hierarchy.Root.Level = Level.Info;
            hierarchy.Configured = true;
        }
예제 #24
0
        public static void RegisterTypes(IUnityContainer container)
        {
            var hierarchy = (Hierarchy)LogManager.GetRepository();
            hierarchy.Root.RemoveAllAppenders();

            hierarchy.Root.Level = Level.Debug;
            hierarchy.RaiseConfigurationChanged(EventArgs.Empty);

            FileAppender fileAppender = new RollingFileAppender();
            fileAppender.AppendToFile = true;
            fileAppender.LockingModel = new FileAppender.MinimalLock();
            fileAppender.File = HttpContext.Current.Server.MapPath("~/TestHarness1.log.txt");
            var patternLayout = new PatternLayout { ConversionPattern = "%d [%2%t] %-5p [%-10c]   %m%n%n" };
            patternLayout.ActivateOptions();

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

            BasicConfigurator.Configure(fileAppender);

            var logger = LogManager.GetLogger(typeof(IServiceBus));

            container.RegisterInstance<ILog>(logger, new ContainerControlledLifetimeManager());

            var ftpClient = new FtpQueueClient();
            ftpClient.ConnectAsync(new Uri("ftp://ftp.jdibble.co.uk/site1/Personal/service-bus-ftp/queue"), new NetworkCredential("jdibble-001", "jli798ik")).Wait();

            container.RegisterInstance<IFtpQueueClient>(ftpClient, new ContainerControlledLifetimeManager());

            container.RegisterType<IQueueManager, FtpQueueManager>(new ContainerControlledLifetimeManager());

            container.RegisterType<SharedMessageHandler>();

            var messageDictionary = new MessageTypeDictionary
                                    {
                                        { ServiceBus.Messaging.MessageExtensions.MessageTypeSignature<SharedMessage>(), typeof(SharedMessage) },
                                        { ServiceBus.Messaging.MessageExtensions.MessageTypeSignature<NonSharedMessage>(), typeof(NonSharedMessage) },
                                        { ServiceBus.Messaging.MessageExtensions.MessageTypeSignature<SharedEvent>(), typeof(SharedEvent) }
                                    };

            container.RegisterInstance<IMessageSerialiser>(new JsonMessageSerialiser(messageDictionary), new ContainerControlledLifetimeManager());

            var serviceBus =
                ServiceBusBuilder.Configure()
                    .WithLogger(container.Resolve<ILog>())
                    .WithHostAddress(new Uri("http://servicebus-ftp.jdibble.co.uk"))
                    .WithHttpTransport(new JsonMessageSerialiser(messageDictionary))
                    .AsMvcServiceBus(RouteTable.Routes, container.Resolve<IQueueManager>())
                    .Build()
                        .WithMessageHandler(container.Resolve<SharedMessageHandler>())
                        .Subscribe(container.Resolve<SharedEventHandler>())
                        .WithPeerAsync(new Peer(new Uri("http://servicebus-ftp2.jdibble.co.uk"))).Result;

            serviceBus.WithPeerAsync(new Peer(new Uri("http://servicebus.jdibble.co.uk")));
            serviceBus.WithPeerAsync(new Peer(new Uri("http://servicebus2.jdibble.co.uk")));

            container.RegisterInstance(serviceBus, new ContainerControlledLifetimeManager());

            container.RegisterType<ServiceBusHub>(new ContainerControlledLifetimeManager());
        }
예제 #25
0
        private static void SetupLoggers()
        {
            var hierarchy = (Hierarchy)LogManager.GetRepository();

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

            var fileAppender = new RollingFileAppender
            {
                AppendToFile = false,
                File = Constants.InstallationLog,
                Layout = patternLayout,
                MaxSizeRollBackups = 3,
                MaximumFileSize = "1GB",
                RollingStyle = RollingFileAppender.RollingMode.Size,
                StaticLogFileName = false
            };
            fileAppender.ActivateOptions();
            hierarchy.Root.AddAppender(fileAppender);

            hierarchy.Root.Level = Level.Info;
            hierarchy.Configured = true;
        }
예제 #26
0
파일: Log.cs 프로젝트: digger1985/MyCode
        protected Log()
        {
            #region конфигурирование FileLog
            //log4net.Config.XmlConfigurator.Configure();//конфиг не происходит, тк очевидно что у либы не может быть app.config-а,
            //а тут он есть, но получается что он "ненастоящий"
            var apender = new RollingFileAppender();
            apender.File = Path.Combine(Furniture.Helpers.LocalAccounts.modelPathResult, "LogUpd.txt");
            if (Path.GetFileName(apender.File) != "LogUpd.txt")
                apender.File = Path.Combine(Furniture.Helpers.LocalAccounts.modelPathResult, "\\LogUpd.txt");
            //apender.File = "D:\\_SWLIB_\\LogUpd.txt";
            apender.AppendToFile = true;
            apender.RollingStyle = RollingFileAppender.RollingMode.Size;
            apender.MaxSizeRollBackups = 0;
            apender.MaximumFileSize = "2MB";
            apender.StaticLogFileName = true;
            apender.Encoding = Encoding.UTF8;
            apender.LockingModel = new FileAppender.MinimalLock();
            apender.Layout = new PatternLayout("%date [%thread] %-5level [%property{NDC}] - %message%newline");
            apender.ActivateOptions();
            FilePath = apender.File;
            File.SetAttributes(FilePath, FileAttributes.Normal);
            #endregion

            log4net.Config.BasicConfigurator.Configure(apender);

            log = LogManager.GetLogger(typeof(Log));
        }
예제 #27
0
        public static void set_file_appender(string output_directory)
        {
            if (!already_configured_file_appender)
            {
                already_configured_file_appender = true;

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

                var rollingFileAppender = new RollingFileAppender
                {
                    Name = "roundhouse.changes.log.appender",
                    File = Path.Combine(Path.GetFullPath(output_directory), "roundhouse.changes.log"),
                    Layout = layout,
                    AppendToFile = false
                };
                rollingFileAppender.ActivateOptions();

                var log = LogManager.GetLogger("roundhouse");
                var logger = (log4net.Repository.Hierarchy.Logger)log.Logger;
                logger.AddAppender(rollingFileAppender);
            
                var nhLog = LogManager.GetLogger("NHibernate.SQL");
                var nhLogger = (log4net.Repository.Hierarchy.Logger)nhLog.Logger;
                nhLogger.AddAppender(rollingFileAppender);
            }
        }
예제 #28
0
        // Create a new file appender
        public static RollingFileAppender CreateFileAppender(LoggerConfigurationElement element)
        {
            var appender = new RollingFileAppender();
            appender.Name = element.LoggerName;
            appender.File = element.Filename;
            appender.AppendToFile = true;
            appender.RollingStyle = RollingFileAppender.RollingMode.Composite;
            appender.MaximumFileSize = element.MaximumFileSize;
            appender.MaxSizeRollBackups = element.MaxSizeRollBackups;
            appender.PreserveLogFileNameExtension = element.PreserveLogFileNameExtension;
            appender.DatePattern = element.DatePattern;

            var layout = new PatternLayout();
            layout.ConversionPattern = "%message";
            layout.ActivateOptions();

            var filter = new LoggerMatchFilter();
            filter.LoggerToMatch = element.LoggerName;
            filter.ActivateOptions();

            var denyAllFilter = new DenyAllFilter();
            denyAllFilter.ActivateOptions();

            appender.AddFilter(filter);
            appender.AddFilter(denyAllFilter);

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

            return appender;
        }
예제 #29
0
		public static void Setup()
		{
			Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

			var patternLayout = new PatternLayout();
			patternLayout.ConversionPattern = "%date{yyyy-MM-dd HH:mm:ss.fff} %-6level  %message%newline";
			patternLayout.ActivateOptions();

			var roller = new RollingFileAppender();
			roller.AppendToFile = true;
			roller.File = LostKeysUnited.Location.FullName + ".log";
			roller.Layout = patternLayout;
			roller.MaxSizeRollBackups = 5;
			roller.MaximumFileSize = "1GB";
			roller.RollingStyle = RollingFileAppender.RollingMode.Size;
			roller.StaticLogFileName = true;
			roller.ActivateOptions();
			hierarchy.Root.AddAppender(roller);
#if DEBUG
			hierarchy.Root.Level = Level.Debug;
#else
			hierarchy.Root.Level = Level.Error;
#endif
			hierarchy.Configured = true;
		}
예제 #30
0
        public static void Initialize()
        {
            var hierarchy = (Hierarchy)LogManager.GetRepository();

            var patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%date %-5level %logger - %message%newline";
            patternLayout.ActivateOptions();

            var roller = new RollingFileAppender();
            roller.AppendToFile = false;
            roller.File = @"Logs\EventLog.txt";
            roller.Layout = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize = "1GB";
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName = true;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            MemoryAppender memory = new MemoryAppender();
            memory.ActivateOptions();
            hierarchy.Root.AddAppender(memory);

            hierarchy.Root.Level = Level.Info;
            hierarchy.Configured = true;
        }
        /// <summary>
        /// Configures the log4net environment
        /// </summary>
        private void Setup(Level logLevel)
        {
            Directory.CreateDirectory(_logFolder);


            var hierarchy = (Hierarchy)LogManager.GetRepository();

            // Log to a file
            var roller = new RollingFileAppender();
            roller.AppendToFile = false;
            roller.File = _logFile;
            roller.Layout = new PatternLayout("%date %type.%method [%-5level] - %message%newline");
            roller.MaxSizeRollBackups = 5;
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName = true;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            // Log to the visual studio console
            var appender = new TraceAppender();
            appender.ActivateOptions();
            appender.Layout = new PatternLayout("%method (%line) %date [%-5level] - %message%newline");
            hierarchy.Root.AddAppender(appender);

            hierarchy.Root.Level = logLevel;
            hierarchy.Configured = true;
        }
예제 #32
0
파일: Logger.cs 프로젝트: dionata/wfmvc
        static Logger()
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
            TraceAppender tracer = new TraceAppender();
            PatternLayout patternLayout = new PatternLayout();

            patternLayout.ConversionPattern = LOG_PATTERN;
            patternLayout.ActivateOptions();

            tracer.Layout = patternLayout;
            tracer.ActivateOptions();
            hierarchy.Root.AddAppender(tracer);

            RollingFileAppender roller = new RollingFileAppender();
            roller.Layout = patternLayout;
            roller.AppendToFile = true;
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.MaxSizeRollBackups = 4;
            roller.MaximumFileSize = "32768KB";
            roller.StaticLogFileName = true;
            roller.File = "log\\Log.log";
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            hierarchy.Root.Level = Level.All;
            hierarchy.Configured = true;
        }
예제 #33
0
        private void CreateLogger(String name, String conversionPattern)
        {
            // Create Appender
            var nameWDate = name + "_" + _time;
            var path = (_path.Equals(""))
                ? @"Logs\" + _date + @"\" + _time.Replace(':', '_') + @"\" + name + ".log"
                : _path + _date + @"\" + _time.Replace(':', '_') + @"\" + name + ".log";
            var appender = new RollingFileAppender()
            {
                Name = nameWDate,
                File = path,
                AppendToFile = true
            };

            // Create Layout
            var layout = new PatternLayout() {ConversionPattern = conversionPattern};
            layout.ActivateOptions();

            // Apply Layout to Appender
            appender.Layout = layout;
            appender.ActivateOptions();

            // Create Logger
            var logger = LogManager.GetLogger(nameWDate);

            // Apply Appender to Logger
            ((log4net.Repository.Hierarchy.Logger) logger.Logger).AddAppender(appender);

            // Add Logger to Dictionary
            _loggers.Add(name, logger);

            XmlConfigurator.Configure();
        }
예제 #34
0
        /// <summary>
        /// 创建日志Ilog
        /// </summary>
        /// <param name="LogPath"></param>
        /// <returns></returns>
        private static ILog CreatLogger(string LogPath)
        {
            var appender = new log4net.Appender.RollingFileAppender();

            appender.AppendToFile = true;
            appender.File         = LogPath;
            //  appender.ImmediateFlush = true;
            // appender.LockingModel = new log4net.Appender.FileAppender.MinimalLock();
            appender.MaxSizeRollBackups = 500;
            appender.MaximumFileSize    = "2MB";
            appender.RollingStyle       = RollingFileAppender.RollingMode.Size;
            appender.StaticLogFileName  = true;

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

            layout.Header = "------ New session ------" + Environment.NewLine;
            layout.Footer = "------ End session ------" + Environment.NewLine;

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

            var repository = log4net.LogManager.CreateRepository("MyRepository" + LogPath);

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

            LogDic.TryAdd(LogPath, logger);
            return(logger);
        }
예제 #35
0
 /// <summary>
 /// 初始化一个<see cref="Log4NetLoggerAdapter"/>类型的新实例
 /// </summary>
 public Log4NetLoggerAdapter()
 {
     const string fileName = "log4net.config";
     string configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
     if (File.Exists(configFile))
     {
         XmlConfigurator.ConfigureAndWatch(new FileInfo(configFile));
         return;
     }
     RollingFileAppender appender = new RollingFileAppender
     {
         Name = "root",
         File = "logs\\log_",
         AppendToFile = true,
         LockingModel = new FileAppender.MinimalLock(),
         RollingStyle = RollingFileAppender.RollingMode.Date,
         DatePattern = "yyyyMMdd-HH\".log\"",
         StaticLogFileName = false,
         MaxSizeRollBackups = 10,
         Layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss.fff}] %-5p %c.%M %t %w %n%m%n")
         //Layout = new PatternLayout("[%d [%t] %-5p %c [%x] - %m%n]")
     };
     appender.ClearFilters();
     appender.AddFilter(new LevelMatchFilter { LevelToMatch = Level.Info });
     //PatternLayout layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss.fff}] %c.%M %t %n%m%n");
     //appender.Layout = layout;
     BasicConfigurator.Configure(appender);
     appender.ActivateOptions();
 }
예제 #36
0
        private static void SetupLoggers()
        {
            var hierarchy = (Hierarchy) LogManager.GetRepository();

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

            var fileAppender = new RollingFileAppender
                {
                    AppendToFile = false,
                    File =
                        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Tailviewer",
                                     "Tailviewer.log"),
                    Layout = patternLayout,
                    MaxSizeRollBackups = 20,
                    MaximumFileSize = "1GB",
                    RollingStyle = RollingFileAppender.RollingMode.Size,
                    StaticLogFileName = false
                };
            fileAppender.ActivateOptions();
            hierarchy.Root.AddAppender(fileAppender);

            hierarchy.Root.Level = Level.Info;
            hierarchy.Configured = true;
        }
예제 #37
0
        public static void Configure()
        {
            if (isConfigured)
            {
                return;
            }

            var loggerName = typeof(DiagnosticsManager).FullName;

            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 = "[Your directory name here. e.c. 'C:\ProgramData\AppName\Logs']";

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

                var fileName = Path.Combine(directoryName, "[Your static file name here. e.c. 'AppName.log']");

                //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{hh:mm:ss.fff} [%thread] %-5level - %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;

            Info("Logging Configured at " + DateTime.Now.ToString("g"));
        }
예제 #38
0
        /// <summary>
        ///
        /// </summary>
        private void ConfigureLogger()
        {
            var repos = LogManager.GetAllRepositories();
            ILoggerRepository repo = null;

            foreach (var r in repos)
            {
                if (r.Name == Run.RunName)
                {
                    repo = r;
                }
            }
            if (repo == null)
            {
                repo = LogManager.CreateRepository(Run.RunName);
            }
            var logger  = repo.GetLogger(Run.RunName);
            var ilogger = repo.GetLogger(Run.RunName);


            var appender = new log4net.Appender.RollingFileAppender();

            appender.Name = "RollingFileAppender";
            appender.File = Path.Combine(Run.RunDirectory, "XTMF.Console.log");
            appender.StaticLogFileName            = true;
            appender.AppendToFile                 = false;
            appender.RollingStyle                 = log4net.Appender.RollingFileAppender.RollingMode.Once;
            appender.MaxSizeRollBackups           = 10;
            appender.MaximumFileSize              = "10MB";
            appender.PreserveLogFileNameExtension = true;
            var layout = new log4net.Layout.PatternLayout()
            {
                ConversionPattern = "%date %-5level %logger - %message%newline"
            };

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

            _consoleAppener = new ConsoleOutputAppender()
            {
                Layout = layout
            };


            //Let log4net configure itself based on the values provided
            appender.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(repo, appender, _consoleAppener);
            iLog = LogManager.GetLogger(Run.RunName, Run.RunName);
        }
예제 #39
0
 static RollingFileAppender CreateRollingFileAppender(string log_path)
 {
     log4net.Appender.RollingFileAppender rfa = new log4net.Appender.RollingFileAppender();
     rfa.Name               = "RollingLogFileAppender";
     rfa.File               = log_path;
     rfa.AppendToFile       = true;
     rfa.RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Date;
     rfa.DatePattern        = "yyyyMMdd'.log'";
     rfa.StaticLogFileName  = false;
     rfa.MaxSizeRollBackups = 100;
     rfa.LockingModel       = new log4net.Appender.FileAppender.MinimalLock();
     rfa.Layout             = new log4net.Layout.PatternLayout("Time:%date ThreadID:[%thread] LogLevel:%-5level %nMessage:%message%n%newline");
     rfa.ActivateOptions();
     return(rfa);
 }
예제 #40
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, bool eventLogs)
        {
            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();

            if (!apiLogs && !eventLogs)
            {
                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 if (apiLogs)
            {
                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";
            }


            else if (eventLogs)
            {
                layout.ConversionPattern = "%message" + "%newline";
                appender.LockingModel    = new log4net.Appender.FileAppender.MinimalLock();
                if (!File.Exists(fileName))
                {
                    layout.Header = "TIMESTAMP                                   SOURCE                  EVENTID                 LEVEL                   MESSAGE\r\n";
                }
            }

            layout.Footer = "END \n";
            layout.ActivateOptions();
            appender.Layout = layout;
            appender.ActivateOptions();

            return(appender);
        }
예제 #41
0
        /// <summary>
        /// Creates a new Rolling File Appender at the specified path with the specified name.
        /// </summary>
        /// <param name="path">The directory path to the log file</param>
        /// <param name="logName">Name of the log.</param>
        private IAppender CreateRollingFileAppender(string path, string logName)
        {
            log4net.Appender.RollingFileAppender rfa = new log4net.Appender.RollingFileAppender();

            rfa.Name               = logName;
            rfa.File               = path + logName;
            rfa.AppendToFile       = true;
            rfa.RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Size;
            rfa.MaxSizeRollBackups = 14;
            rfa.CountDirection     = 1;
            rfa.MaximumFileSize    = "15000KB";
            rfa.StaticLogFileName  = true;
            rfa.Layout             = new log4net.Layout.PatternLayout(@"%d [%t] %-5p %c %n%m%n------------------------------------------------------------------------------------------%n");
            rfa.ActivateOptions();
            rfa.Threshold = log4net.Core.Level.Debug;

            return(rfa);
        }
        private static IAppender createRollingFileAppender(int rank)
        {
            log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
            appender.Name               = "Executor" + rank + "RollingFileAppender";
            appender.File               = CommonStartInfo.logsDirectory + "\\Executor" + rank + "Process-log.txt";
            appender.AppendToFile       = true;
            appender.RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Size;
            appender.MaxSizeRollBackups = 10;
            appender.MaximumFileSize    = "5MB";
            appender.StaticLogFileName  = true;

            PatternLayout layout = new PatternLayout();

            layout.ConversionPattern = "%date - %m%n";
            layout.ActivateOptions();

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

            return(appender);
        }
예제 #43
0
 private void ChangeLog4netLogFileName(log4net.ILog iLog, string fileName)
 {
     log4net.Core.LogImpl logImpl = iLog as log4net.Core.LogImpl;
     if (logImpl != null)
     {
         log4net.Appender.AppenderCollection ac = ((log4net.Repository.Hierarchy.Logger)logImpl.Logger).Appenders;
         for (int i = 0; i < ac.Count; i++)
         {     // 这里我只对RollingFileAppender类型做修改
             log4net.Appender.RollingFileAppender rfa = ac[i] as log4net.Appender.RollingFileAppender;
             if (rfa != null)
             {
                 rfa.File = fileName;
                 if (!System.IO.File.Exists(fileName))
                 {
                     System.IO.File.Create(fileName);
                 }
                 // 更新Writer属性
                 rfa.Writer = new  System.IO.StreamWriter(rfa.File, rfa.AppendToFile, rfa.Encoding);
             }
         }
     }
 }
예제 #44
0
        public static log4net.Appender.IAppender CreateFileAppender(string name, string fileName, string levelName)
        {
            string AppDataPath = T1.Log.Settings._Main.logFolder;


            log4net.Appender.RollingFileAppender appender = new
                                                            log4net.Appender.RollingFileAppender();
            try {
                appender.Name               = name + T1.Log.Settings._Main.appenderSufix;
                appender.File               = AppDataPath + fileName + ".log";
                appender.AppendToFile       = true;
                appender.RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Size;
                appender.MaxSizeRollBackups = Settings._Main.numberOfLogs;
                appender.MaximumFileSize    = T1.Log.Settings._Main.masterSize;
                appender.CountDirection     = 1;

                log4net.Layout.PatternLayout layout = new
                                                      log4net.Layout.PatternLayout();
                layout.ConversionPattern = T1.Log.Settings._Main.pattern;
                layout.ActivateOptions();

                log4net.Filter.LevelRangeFilter filter = new log4net.Filter.LevelRangeFilter();
                switch (levelName)
                {
                case "All":
                    filter.LevelMin = log4net.Core.Level.All;
                    break;

                case "Alert":
                    filter.LevelMin = log4net.Core.Level.Alert;
                    break;

                case "Debug":
                    filter.LevelMin = log4net.Core.Level.Debug;
                    break;

                case "Critical":
                    filter.LevelMin = log4net.Core.Level.Critical;
                    break;

                case "Error":
                    filter.LevelMin = log4net.Core.Level.Error;
                    break;

                case "Fatal":
                    filter.LevelMin = log4net.Core.Level.Fatal;
                    break;

                case "Info":
                    filter.LevelMin = log4net.Core.Level.Info;
                    break;

                case "Warn":
                    filter.LevelMin = log4net.Core.Level.Warn;
                    break;

                default:
                    filter.LevelMin = log4net.Core.Level.All;
                    break;
                }



                filter.ActivateOptions();

                appender.Layout = layout;
                appender.AddFilter(filter);

                appender.ActivateOptions();
            }
            catch (Exception er)
            {
                using (StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\FatalLogError.log", true))
                {
                    sw.WriteLine(er.Message);
                }
            }

            return(appender);
        }
예제 #45
0
        public static log4net.Appender.IAppender CreateFileAppender(string name, string fileName, string levelName)
        {
            log4net.Appender.RollingFileAppender appender = new
                                                            log4net.Appender.RollingFileAppender();
            appender.Name               = name + Settings._Main.appenderSufix;
            appender.File               = Settings._Main.logFolder + fileName + ".log";
            appender.AppendToFile       = true;
            appender.RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Size;
            appender.MaxSizeRollBackups = 5;
            appender.MaximumFileSize    = Settings._Main.masterSize;
            appender.CountDirection     = 1;

            log4net.Layout.PatternLayout layout = new
                                                  log4net.Layout.PatternLayout();
            layout.ConversionPattern = Settings._Main.pattern;
            layout.ActivateOptions();

            log4net.Filter.LevelRangeFilter filter = new log4net.Filter.LevelRangeFilter();
            switch (levelName)
            {
            case "All":
                filter.LevelMin = log4net.Core.Level.All;
                break;

            case "Alert":
                filter.LevelMin = log4net.Core.Level.Alert;
                break;

            case "Debug":
                filter.LevelMin = log4net.Core.Level.Debug;
                break;

            case "Critical":
                filter.LevelMin = log4net.Core.Level.Critical;
                break;

            case "Error":
                filter.LevelMin = log4net.Core.Level.Error;
                break;

            case "Fatal":
                filter.LevelMin = log4net.Core.Level.Fatal;
                break;

            case "Info":
                filter.LevelMin = log4net.Core.Level.Info;
                break;

            case "Warn":
                filter.LevelMin = log4net.Core.Level.Warn;
                break;

            default:
                filter.LevelMin = log4net.Core.Level.All;
                break;
            }



            filter.ActivateOptions();

            appender.Layout = layout;
            appender.AddFilter(filter);

            appender.ActivateOptions();

            return(appender);
        }