Пример #1
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);
            }
        }
 private void addConveters(PatternLayout patternLayout)
 {
     foreach (ConverterInfo conveterInfo in m_converters)
     {
         patternLayout.AddConverter(conveterInfo);
     }
 }
 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;
 }
Пример #4
0
 public static void AddConsoleLogger()
 {
     ConsoleAppender consoleLog = new ConsoleAppender();
     PatternLayout patternLayout = new PatternLayout(config.PatternFormat);
     consoleLog.Layout = patternLayout;
     AddAppender(consoleLog);
 }
Пример #5
0
    /// <summary>
    /// Configures the <see cref="FileLogger"/> logger adding the appenders to
    /// the root repository.
    /// </summary>
    /// <remarks></remarks>
    public void Configure() {
      // create a new logger into the repository of the current assembly.
      ILoggerRepository root_repository =
        LogManager.GetRepository(Assembly.GetExecutingAssembly());

      Logger nohros_file_logger =
        root_repository.GetLogger("NohrosFileAppender") as Logger;

      // create the layout and appender for log messages
      PatternLayout layout = new PatternLayout();
      layout.ConversionPattern = layout_pattern_;
      layout.ActivateOptions();

      FileAppender appender = new FileAppender();
      appender.Name = "NohrosCommonFileAppender";
      appender.File = log_file_path_;
      appender.AppendToFile = true;
      appender.Layout = layout;
      appender.Threshold = Level.All;
      appender.ActivateOptions();

      // add the appender to the root repository
      nohros_file_logger.Parent.AddAppender(appender);

      root_repository.Configured = true;

      logger = LogManager.GetLogger("NohrosFileLogger");
    }
		public void SimpleTest()
		{
			container.AddComponent("component1", typeof(SimpleLoggingComponent));
			SimpleLoggingComponent test = container["component1"] as SimpleLoggingComponent;

			test.DoSomething();

			String expectedLogOutput = String.Format("[INFO ] [{0}] - Hello world" + Environment.NewLine, typeof(SimpleLoggingComponent).FullName);
			MemoryAppender memoryAppender = ((Hierarchy)LogManager.GetRepository()).Root.GetAppender("memory") as MemoryAppender;
			TextWriter actualLogOutput = new StringWriter();
			PatternLayout patternLayout = new PatternLayout("[%-5level] [%logger] - %message%newline");
			patternLayout.Format(actualLogOutput, memoryAppender.GetEvents()[0]);

			Assert.AreEqual(expectedLogOutput, actualLogOutput.ToString());

			container.AddComponent("component2", typeof(SmtpServer));
			ISmtpServer smtpServer = container["component2"] as ISmtpServer;

			smtpServer.Start();
			smtpServer.InternalSend("*****@*****.**", "*****@*****.**", "We're looking for a few good porgrammars.");
			smtpServer.Stop();

			expectedLogOutput = String.Format("[DEBUG] [Castle.Facilities.Logging.Tests.Classes.SmtpServer] - Stopped" + Environment.NewLine, typeof(SimpleLoggingComponent).FullName);
			memoryAppender = ((Hierarchy)LogManager.GetRepository()).Root.GetAppender("memory") as MemoryAppender;
			actualLogOutput = new StringWriter();
			patternLayout = new PatternLayout("[%-5level] [%logger] - %message%newline");

			Assert.AreEqual(memoryAppender.GetEvents().Length, 4);

			patternLayout.Format(actualLogOutput, memoryAppender.GetEvents()[3]);

			Assert.AreEqual(expectedLogOutput, actualLogOutput.ToString());
		}
Пример #7
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();
        }
        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;
        }
        /// <summary>
        /// Setup Log4NET logger.
        /// </summary>
        internal static void Setup()
        {
            var hierarchy = (Hierarchy) LogManager.GetRepository();

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

            var roller = new FileAppender
            {
                AppendToFile = false,
                File = @"AllureLog.txt",
                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;
        }
Пример #10
0
        /// <summary>
        /// Contiene la logica para crear un appender FICHERO
        /// </summary>
        /// <param name="nombreAppender">Nombre del appender</param>
        /// <param name="nombreFichero">Nombre del fichero</param>
        /// <param name="patronConversion"> Si se deja a null el valor por defecto es %d [%t] %-5p %c [%x] - %m%n </param>
        /// <returns>Retorna el appender creado</returns>
        public static IAppender CrearAppenderFichero(string nombreAppender, string nombreFichero, string patronConversion)
        {
            var appender = new FileAppender
            {
                Name = nombreAppender,
                File = nombreFichero,
                AppendToFile = true
            };

            var patronConversionAux = "%d [%t] %-5p %c [%x] - %m%n";
            if(patronConversion != null && !patronConversion.Equals(string.Empty))
            {
                patronConversionAux = patronConversion;
            }

            var layout = new PatternLayout
            {
                ConversionPattern = patronConversionAux
            };
            layout.ActivateOptions();

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

            return appender;
        }
Пример #11
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;
        }
Пример #12
0
        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;
        }
        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);
        }
        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;
        }
Пример #15
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;
        }
Пример #16
0
        public void Configure()
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
            hierarchy.Root.RemoveAllAppenders(); /*Remove any other appenders*/

            FileAppender fileAppender = new FileAppender();
            fileAppender.AppendToFile = true;
            fileAppender.LockingModel = new FileAppender.MinimalLock();
            fileAppender.File = _locationProvider.GetFilePath();
            PatternLayout pl = new PatternLayout();
            pl.ConversionPattern = "%d [%2%t] %-5p [%-10c]   %m%n%n";
            pl.ActivateOptions();
            fileAppender.Layout = pl;
            fileAppender.ActivateOptions();

            ConsoleAppender consoleAppender = new ConsoleAppender();
            consoleAppender.Layout = pl;
            consoleAppender.ActivateOptions();

            //            log4net.Config.BasicConfigurator.Configure(fileAppender);
            IAppender[] appenders = {fileAppender, consoleAppender};
            log4net.Config.BasicConfigurator.Configure(appenders);
            var log = LogManager.GetLogger(GetType());
            log.Debug("Logging Configured");
        }
Пример #17
0
 private static ColoredConsoleAppender GetColoredConsoleAppender(PatternLayout patternLayout)
 {
     ColoredConsoleAppender coloredConsoleAppender = new ColoredConsoleAppender();
     coloredConsoleAppender.AddMapping(new ColoredConsoleAppender.LevelColors
         {
             Level = Level.Fatal,
             ForeColor = ColoredConsoleAppender.Colors.Red | ColoredConsoleAppender.Colors.HighIntensity
         });
     coloredConsoleAppender.AddMapping(new ColoredConsoleAppender.LevelColors
         {
             Level = Level.Error,
             ForeColor = ColoredConsoleAppender.Colors.Red | ColoredConsoleAppender.Colors.HighIntensity
         });
     coloredConsoleAppender.AddMapping(new ColoredConsoleAppender.LevelColors
         {
             Level = Level.Warn,
             ForeColor = ColoredConsoleAppender.Colors.Yellow | ColoredConsoleAppender.Colors.HighIntensity
         });
     coloredConsoleAppender.AddMapping(new ColoredConsoleAppender.LevelColors
         {
             Level = Level.Info,
             ForeColor = ColoredConsoleAppender.Colors.White
         });
     coloredConsoleAppender.AddMapping(new ColoredConsoleAppender.LevelColors
         {
             Level = Level.Debug,
             ForeColor = ColoredConsoleAppender.Colors.Green
         });
     coloredConsoleAppender.Layout = patternLayout;
     coloredConsoleAppender.Threshold = Level.All;
     coloredConsoleAppender.ActivateOptions();
     return coloredConsoleAppender;
 }
Пример #18
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());
        }
		public Log4NetConsoleFactory(LogLevel level)
		{
			var hierarchy = (Hierarchy)global::log4net.LogManager.GetRepository();
			hierarchy.Root.RemoveAllAppenders();

			var layout = new PatternLayout { ConversionPattern = "%utcdate{ISO8601} [%thread] %-3level %-8logger{1} - %message%newline" };
			layout.ActivateOptions();

			var appender = new ColoredConsoleAppender
			{
				Layout = layout,
				Threshold = ToLog4NetLevel(level)
			};

			appender.AddMapping(new ColoredConsoleAppender.LevelColors { ForeColor = ColoredConsoleAppender.Colors.HighIntensity, Level = Level.Debug });
			appender.AddMapping(new ColoredConsoleAppender.LevelColors { ForeColor = ColoredConsoleAppender.Colors.Cyan, Level = Level.Info });
			appender.AddMapping(new ColoredConsoleAppender.LevelColors { ForeColor = ColoredConsoleAppender.Colors.White, BackColor = ColoredConsoleAppender.Colors.Yellow, Level = Level.Warn });
			appender.AddMapping(new ColoredConsoleAppender.LevelColors { ForeColor = ColoredConsoleAppender.Colors.White, BackColor = ColoredConsoleAppender.Colors.Red, Level = Level.Error });
			appender.AddMapping(new ColoredConsoleAppender.LevelColors { ForeColor = ColoredConsoleAppender.Colors.White, BackColor = ColoredConsoleAppender.Colors.Red, Level = Level.Fatal });

			appender.ActivateOptions();

			hierarchy.Root.AddAppender(appender);
			hierarchy.Configured = true;
		}
Пример #20
0
		public static void BindConsole(PatternLayout layout = null, Level level = null)
		{
			layout = layout ?? new PatternLayout
			{
				ConversionPattern = "%date{ISO8601} %level %logger - %message%newline"
			};

			layout.ActivateOptions();

			var consoleAppender = new ConsoleAppender
			{
				Name = "console",
				Layout = layout
			};

			consoleAppender.ActivateOptions();

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

			if (hierarchy.Root.GetAppender("console") != null)
			{
				return;
			}

			hierarchy.Root.AddAppender(consoleAppender);
			hierarchy.Root.Level = level ?? Level.Info;

			hierarchy.Configured = true;
		}
Пример #21
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;
        }
    public static void ConfigureLog4Net()
    {
        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 appender = new RollingFileAppender
        {
            DatePattern = "yyyy-MM-dd'.txt'",
            RollingStyle = RollingFileAppender.RollingMode.Composite,
            MaxFileSize = 10 * 1024 * 1024,
            MaxSizeRollBackups = 10,
            LockingModel = new FileAppender.MinimalLock(),
            StaticLogFileName = false,
            File =  @"nsb_log_",
            Layout = layout,
            AppendToFile = true,
            Threshold = Level.Debug,
        };
        appender.ActivateOptions();

        BasicConfigurator.Configure(appender, consoleAppender);
    }
Пример #23
0
        public void TestThreadSafety()
        {
            ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
            var memoryAppender = new MemoryAppender();
            var patternLayout = new PatternLayout();
            memoryAppender.Layout = patternLayout;
            memoryAppender.ActivateOptions();
            BasicConfigurator.Configure(rep, memoryAppender);

            cThreadsRunning = cThreadsMax;
            var threads = Enumerable.Range(0, cThreadsMax)
                .Select(i => new Thread(LogMessages(rep.Name)))
                .ToList();

            foreach (var thread in threads)
            {
                thread.Start();
            }

            long cEventsRead = 0;
            while (cThreadsRunning > 0)
            {
                var events = memoryAppender.PopAllEvents();
                cEventsRead += events.Length;
            }
            foreach (var thread in threads)
            {
                thread.Join();
            }
	    cEventsRead += memoryAppender.PopAllEvents().Length;
            Assert.AreEqual(cEventsExpected, cEventsRead, "Log events were lost.");
        }
        /// <summary>
        /// Init log4net memoryAppender 
        /// http://dhvik.blogspot.com/2008/08/adding-appender-to-log4net-in-runtime.html
        /// </summary>
        void InitLogger()
        {
            //First create and configure the appender
            this.memoryAppender = new MemoryAppender();
            this.memoryAppender.Name = this.GetType().Name + "MemoryAppender";

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

            //Notify the appender on the configuration changes
            this.memoryAppender.ActivateOptions();

            //Get the logger repository hierarchy.
            this.repository = (Hierarchy)LogManager.GetRepository();

            //and add the appender to the root level
            //of the logging hierarchy
            this.repository.Root.AddAppender(memoryAppender);

            //configure the logging at the root.
            //this.repository.Root.Level = Level.Info;

            //mark repository as configured and notify that is has changed.
            this.repository.Configured = true;
            this.repository.RaiseConfigurationChanged(EventArgs.Empty);

            this.msgWriter = new StringWriter();
        }
Пример #25
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // gather log4net output with small hack to get results...
        ILoggerRepository repository = LogManager.GetRepository();
        IAppender[] appenders = repository.GetAppenders();
        MemoryAppender appender = null;
        foreach (IAppender a in appenders)
        {
            if (a is MemoryAppender)
            {
                // we found our appender to look results from
                appender = a as MemoryAppender;
                break;
            }
        }

        if (appender != null)
        {
            appender.Clear();
            fulfillmentService.ProcessCustomer(customerEditController.CurrentCustomer.Id);
            LoggingEvent[] events = appender.GetEvents();
            StringWriter stringWriter = new StringWriter();
            PatternLayout layout = new PatternLayout("%date{HH:mm:ss} %-5level %logger{1}: %message<br />");
            foreach (LoggingEvent loggingEvent in events)
            {
                layout.Format(stringWriter, loggingEvent);
            }

            results.Text = stringWriter.ToString();
        }

    }
Пример #26
0
 public AzureQueueAppender()
 {
     PatternLayout layout = new PatternLayout();
     layout.ConversionPattern = PatternLayout.DetailConversionPattern;
     layout.ActivateOptions();
     Layout = layout;
 }
Пример #27
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);
        }
        private void ConfigureRepositoryWithLayoutWithMessageProperties(PatternLayout layout)
        {
            LogManager.Shutdown();

            _Rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
            _Appender = new RabbitMQAppender { Layout = layout };
            _Appender.ExchangeProperties.Name = "log4Net.RabbitMQ.Tests";
            _Appender.ExchangeProperties.ExchangeType = "fanout";
            _Appender.ExchangeProperties.Durable = true;

            _Appender.MessageProperties.AppId = Guid.NewGuid().ToString();
            _Appender.MessageProperties.ContentType = new PatternLayout("text/plain");
            _Appender.MessageProperties.Persistent = true;
            _Appender.MessageProperties.Priority = new PatternLayout("%property{priority}");
            _Appender.MessageProperties.Topic = new PatternLayout("%property{topic}");

            // An app could do something like this to customize the message priority and routing key on a message by message 
            // basis.

            ThreadContext.Properties["priority"] = "0";
            ThreadContext.Properties["topic"] = "log4net.RabbitMQ.Tests";

            _Appender.HostName = this.hostName;

            _Appender.ActivateOptions();

            BasicConfigurator.Configure(_Rep, _Appender);
            _Log = LogManager.GetLogger(_Rep.Name, GetType());

            BasicConfigurator.Configure(new ConsoleAppender { Layout = new SimpleLayout() });
        }
Пример #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
    /// <summary>
    /// Configures the <see cref="FileLogger"/> logger adding the appenders
    /// to the root repository.
    /// </summary>
    public void Configure() {
      // create a new logger into the repository of the current assembly.
      ILoggerRepository root_repository =
        LogManager.GetRepository(Assembly.GetExecutingAssembly());

      Logger nohros_console_logger =
        root_repository.GetLogger("NohrosConsoleLogger") as Logger;

      // create the layout and appender for on error messages.
      PatternLayout layout = new PatternLayout();
      layout.ConversionPattern = layout_pattern_;
      layout.ActivateOptions();

      // create the appender
      ConsoleAppender appender = new ConsoleAppender();
      appender.Name = "NohrosCommonConsoleAppender";
      appender.Layout = layout;
      appender.Target = "Console.Out";
      appender.Threshold = Level.All;
      appender.ActivateOptions();

      nohros_console_logger.Parent.AddAppender(appender);

      root_repository.Configured = true;

      logger = LogManager.GetLogger("NohrosConsoleLogger");
    }
Пример #31
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();
        }
Пример #32
0
        private void initLog(string fileName, bool append)
        {
            Hierarchy hierarchy = (Hierarchy)log4net.LogManager.GetRepository();

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

            log4net.Appender.FileAppender fa = new log4net.Appender.FileAppender();
            fa.Layout       = pl;
            fa.LockingModel = new FileAppender.MinimalLock();
            DateTime today = DateTime.Today;

            fa.File         = @"log" + Path.DirectorySeparatorChar + fileName + mExtensionName;
            fa.AppendToFile = append;
            fa.ActivateOptions();

            log4net.Config.BasicConfigurator.Configure(fa);
        }
Пример #33
0
    public Logging(string sFileName, string sLocation, bool bUseLogging)
    {
        m_sFileName = sFileName;
        if (!bUseLogging)
        {
            return;
        }

        if (sLocation.Length > 0)
        {
            if (sLocation[sLocation.Length - 1] != '\\')
            {
                sLocation += "\\";
            }
        }

        m_RFL      = new log4net.Appender.RollingFileAppender();
        m_RFL.File = sLocation + m_sFileName + m_sFileExt;
        m_RFL.StaticLogFileName  = true;
        m_RFL.AppendToFile       = true;
        m_RFL.RollingStyle       = log4net.Appender.RollingFileAppender.RollingMode.Size;
        m_RFL.MaximumFileSize    = "10mb";
        m_RFL.MaxSizeRollBackups = 2;
        m_RFL.Threshold          = log4net.Core.Level.All;

        //m_RFL.CountDirection = 1;
        //m_RFL.DatePattern = "HH:MM::SS";
        log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout("%message%newline");
        layout.ActivateOptions();
        log4net.Filter.LevelRangeFilter filter = new log4net.Filter.LevelRangeFilter();
        filter.LevelMax = log4net.Core.Level.Emergency;
        filter.LevelMin = log4net.Core.Level.All;
        m_RFL.AddFilter(filter);
        m_RFL.Layout = layout;
        m_RFL.ActivateOptions();

        log4net.Config.BasicConfigurator.Configure(m_RFL);

        // Set up
        Log(Logging.LOGTYPE.ERROR, "Start logging...");
    }
Пример #34
0
    public static void ConfigureLogging()
    {
        var pl = new log4net.Layout.PatternLayout
        {
            ConversionPattern = "%d [%t] %-5p %c [%x] <%X{auth}> - %m%n"
        };

        pl.ActivateOptions();

        var fileAppender = new RollingFileAppender
        {
            CountDirection     = 1,
            DatePattern        = "yyyy-MM-dd",
            RollingStyle       = RollingFileAppender.RollingMode.Composite,
            MaxFileSize        = 1024 * 1024,
            MaxSizeRollBackups = 10,
            LockingModel       = new FileAppender.MinimalLock(),
            StaticLogFileName  = true,
            File           = "logfile.txt",
            AppendToFile   = true,
            ImmediateFlush = true,
            Layout         = pl
        };

        fileAppender.ActivateOptions();

        var consoleAppender = new ColoredConsoleAppender();

        PrepareColors(consoleAppender);
        consoleAppender.Threshold = Level.Info;
        consoleAppender.Layout    = pl;
        consoleAppender.ActivateOptions();

        ((Hierarchy)LogManager.GetRepository()).Root.RemoveAllAppenders();

        BasicConfigurator.Configure(fileAppender, consoleAppender);
        NServiceBus.Logging.LogManager.Use <Log4NetFactory>();
    }
Пример #35
0
    // check if the logging system uses UnityLog4NetAppender
    private bool CheckForUnityAppender()
    {
        log4net.Repository.Hierarchy.Hierarchy hierarchy = log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy;
        if (hierarchy.Root.Appenders.Count > 0)
        {
            foreach (log4net.Appender.IAppender appender in hierarchy.Root.Appenders)
            {
                if (appender is UnityLog4NetAppender)
                {
                    if (!LogSDKDebug)
                    {
                        (appender as UnityLog4NetAppender).Threshold = log4net.Core.Level.Info;
                    }
                    return(true);
                }
            }
            return(false);
        }
        else
        {
            // if we got here the is no configuration for the logger
            hierarchy.Root.RemoveAllAppenders(); /*Remove any other appenders*/

            UnityLog4NetAppender         unityAppender = new UnityLog4NetAppender();
            log4net.Layout.PatternLayout pl            = new log4net.Layout.PatternLayout();
            pl.ConversionPattern = "%m";
            pl.ActivateOptions();
            unityAppender.Layout = pl;
            if (!LogSDKDebug)
            {
                (unityAppender as UnityLog4NetAppender).Threshold = log4net.Core.Level.Info;
            }
            unityAppender.ActivateOptions();

            log4net.Config.BasicConfigurator.Configure(unityAppender);
            return(true);
        }
    }
        private void addNewAppender(int?logLevel, string pattern)
        {
            RollingFileAppender classAppender = Logger.GetAppenders(className, null);
            Hierarchy           hierarchy     = (Hierarchy)LogManager.GetRepository();
            PatternLayout       patternLayout = new PatternLayout();

            if (pattern == null)
            {
                if (classAppender != null)
                {
                    if (classAppender.Layout != null)
                    {
                        log4net.Layout.PatternLayout layout = (log4net.Layout.PatternLayout)classAppender.Layout;
                        patternLayout.ConversionPattern = layout.ConversionPattern;
                    }
                    else
                    {
                        patternLayout.ConversionPattern = fullMsgConversionPattern;
                    }
                }
                else
                {
                    patternLayout.ConversionPattern = fullMsgConversionPattern;
                }
            }
            else
            {
                patternLayout.ConversionPattern = pattern;
            }
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();

            roller.Layout       = patternLayout;
            roller.Name         = appenderName;
            roller.RollingStyle = RollingFileAppender.RollingMode.Composite;
            roller.PreserveLogFileNameExtension = true;
            roller.StaticLogFileName            = false;
            roller.AppendToFile = true;
            roller.File         = logFileName;
            roller.DatePattern  = "yyyyMMdd-HH";
            if (classAppender != null)
            {
                //   roller.File = classAppender.File;
                roller.MaxSizeRollBackups = classAppender.MaxSizeRollBackups;
                roller.MaximumFileSize    = classAppender.MaximumFileSize;
                roller.Threshold          = classAppender.Threshold;
            }
            else
            {
                roller.MaxSizeRollBackups = 100;
                roller.MaximumFileSize    = "10MB";
            }
            roller.ActivateOptions();


            log4net.ILog log = log4net.LogManager.GetLogger(serverName + "_" + className);
            ((log4net.Repository.Hierarchy.Logger)log.Logger).AddAppender(roller);
            // hierarchy.Root.AddAppender(roller);

            //  hierarchy.Root.Level = GetLogLevel(logLevel);
            hierarchy.Configured = true;
        }
Пример #37
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);
        }
Пример #38
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);
        }