Пример #1
0
        /// <summary>
        /// Writer
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="module">The module.</param>
        /// <param name="fileFormat">The file format.</param>
        /// <param name="filePath">The file path.</param>
        /// <remarks>
        /// <list>
        ///   <item>
        ///     <description>说明原因 added by Shaipe 2018/11/6</description>
        ///   </item>
        /// </list></remarks>
        public static void Writer(string content, string module = "log", string fileFormat = "log{0}.log", string filePath = "")
        {
            //获取一个可写锁
            m_appenderLock.AcquireWriterLock();

            try
            {
                TextWriterAppender appender = null;

                if (string.IsNullOrEmpty(filePath))
                {
                    filePath = LogFolder;
                }

                lock (Singleton.Instance)
                {
                    if (!AppenderContailer.Appenders.ContainsKey(module))
                    {
                        appender = new FileAppender(filePath, module, fileFormat, true);
                        AppenderContailer.Appenders.Add(module, appender);
                    }
                    else
                    {
                        appender = AppenderContailer.Appenders[module];
                    }

                    appender.DoAppend(content + "\r\n");
                }
            }
            finally
            {
                m_appenderLock.ReleaseWriterLock();
            }
        }
        public void Test_LogHttpRequest()
        {
            // Force log initialization
            Logger logger = new Logger(typeof(HttpUtilitiesTest).ToString());

            // Reset current configuration
            LogManager.ResetConfiguration();

            // Redirect log output to strinb guilder
            StringBuilder      sb       = new StringBuilder();
            TextWriterAppender appender = new TextWriterAppender();

            appender.Writer    = new StringWriter(sb);
            appender.Threshold = log4net.Core.Level.Debug;
            appender.Layout    = new log4net.Layout.PatternLayout();
            appender.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(appender);

            // Initialize current request
            string userIdentity = Guid.NewGuid().ToString();

            MockHttpContext.InitializeCurrentContext();
            HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(userIdentity), null);

            // Log and test
            Esapi.HttpUtilities.LogHttpRequest(HttpContext.Current.Request, Esapi.Logger, null);
            Assert.IsFalse(string.IsNullOrEmpty(sb.ToString()));
            Assert.IsTrue(sb.ToString().Contains(userIdentity));
        }
Пример #3
0
        // - - - - - - - - - - - - - - - - - - - - - - - - - - -


        private void _EndStoreLogMessages()
        {
            if (appenderLogMessages != null)
            {
                appenderLogMessages.Close();
                (log.Logger as IAppenderAttachable).RemoveAppender(appenderLogMessages);
                appenderLogMessages = null;
            }
        }
Пример #4
0
        /// <summary>
        /// 按照记录日志事件指定的格式
        /// </summary>
        /// <param name="loggingEvent">日志事件</param>
        /// <param name="layout">记录日志格式</param>
        virtual public void Log(LoggingEvent loggingEvent, ILayout layout)
        {
            if (loggingEvent == null)
            {
                throw new ArgumentNullException("loggingEvent");
            }

            if (loggingEvent.EventData == null)
            {
                throw new NullReferenceException("记录日志事件数据不能为空");
            }

            if (String.IsNullOrEmpty(loggingEvent.EventData.LogCode))
            {
                throw new NullReferenceException("记录日志事件日志编码不能为空");
            }

            if (String.IsNullOrEmpty(loggingEvent.EventData.Module))
            {
                throw new NullReferenceException("记录日志事件模块名称不能为空");
            }

            if (String.IsNullOrEmpty(loggingEvent.EventData.Message))
            {
                throw new NullReferenceException("记录日志事件日志信息不能为空");
            }

            m_appenderLock.AcquireWriterLock();

            try
            {
                TextWriterAppender appender = null;

                lock (Singleton.Instance)
                {
                    if (!AppenderContailer.Appenders.ContainsKey(loggingEvent.EventData.Module))
                    {
                        appender = new FileAppender(LogFolder, true, loggingEvent.EventData.Module, layout);
                        AppenderContailer.Appenders.Add(loggingEvent.EventData.Module, appender);
                    }
                    else
                    {
                        appender = AppenderContailer.Appenders[loggingEvent.EventData.Module];
                    }

                    appender.DoAppend(loggingEvent);
                }
            }
            finally
            {
                m_appenderLock.ReleaseWriterLock();
            }
        }
Пример #5
0
 public TextLogSpy(string loggerName, string pattern)
 {
     stringBuilder = new StringBuilder();
     appender      = new TextWriterAppender
     {
         Layout    = new PatternLayout(pattern),
         Threshold = Level.All,
         Writer    = new StringWriter(stringBuilder)
     };
     loggerImpl = (Logger)LogManager.GetLogger(loggerName).Logger;
     loggerImpl.AddAppender(appender);
     loggerImpl.Level = Level.All;
 }
Пример #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        public MainWindow()
        {
            this.InitializeComponent();
            TextWriterAppender boxLogger = log4net.LogManager.GetRepository().GetAppenders().OfType <TextWriterAppender>().FirstOrDefault(a => a.Name == "TextBoxAppender");

            if (boxLogger != null)
            {
                boxLogger.Writer = new TextBoxTextWriter(this.logBox);
            }

            Instance = this;
            this.StartProviderAsync();
        }
        public void SetUp()
        {
            XmlDocument xmlDoc      = new XmlDocument();
            XmlElement  log4NetNode = xmlDoc.CreateElement(Log4NetXmlConstants.Log4Net);

            IElementConfiguration configuration = Substitute.For <IElementConfiguration>();

            configuration.ConfigXml.Returns(xmlDoc);
            configuration.Log4NetNode.Returns(log4NetNode);

            mSut = new TextWriterAppender(configuration);
            mSut.Initialize();
        }
Пример #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        public MainWindow()
        {
            this.InitializeComponent();
            this.hostedProvider.ProcessRequest = this.ProcessRequest;
            TextWriterAppender boxLogger = log4net.LogManager.GetRepository().GetAppenders().OfType <TextWriterAppender>().FirstOrDefault(a => a.Name == "TextBoxAppender");

            if (boxLogger != null)
            {
                boxLogger.Writer = new TextBoxTextWriter(this.logBox);
            }

            this.startProvider();
        }
Пример #9
0
 public TextLogSpy(string loggerName, string pattern)
 {
     stringBuilder = new StringBuilder();
     appender      = new TextWriterAppender
     {
         Layout    = new PatternLayout(pattern),
         Threshold = Level.All,
         Writer    = new StringWriter(stringBuilder)
     };
     loggerImpl = (Logger)LogManager.GetLogger(typeof(LogsFixtureAsync).Assembly, loggerName).Logger;
     loggerImpl.AddAppender(appender);
     previousLevel    = loggerImpl.Level;
     loggerImpl.Level = Level.All;
 }
Пример #10
0
        /// <summary>
        /// Tracing setup.
        /// </summary>
        public void InitTraceFile(SessionInfo si)
        {
            if (logger_output != null)
            {
                throw new ApplicationException("Already called."); // is seems this object is designed so that it stores at max one session per lifetime
            }
            var id = si.ID;

            // create tracer
            // =============

            int Rank = MyRank;

            Stream tracerfile = null;

            if (fsDriver != null && id != Guid.Empty)
            {
                tracerfile = this.FsDriver.GetNewLogStream("trace." + Rank, id);
            }

            TextWriter tracertxt = null;

            if (tracerfile == null && Tracer.NamespacesToLog.Length > 0 && !configAllreadyDone)
            {
                // create trace file in local directory

                string tracefilename = "trace." + Rank + ".txt";
                tracerfile = new FileStream(tracefilename, FileMode.Create, FileAccess.Write, FileShare.Read);
            }

            if (tracerfile != null)
            {
                //var zipper = new System.IO.Compression.GZipStream(tracerfile, System.IO.Compression.CompressionMode.Compress);
                //tracertxt = new StreamWriter(zipper);
                tracertxt = new StreamWriter(tracerfile);
            }

            if (tracertxt != null)
            {
                TextWriterAppender fa = new TextWriterAppender();
                fa.ImmediateFlush = true;
                //fa.Writer = Console.Out;
                fa.Writer = tracertxt;
                fa.Layout = new PatternLayout("%date %-5level %logger: %message%newline");
                fa.ActivateOptions();
                BasicConfigurator.Configure(fa);
                logger_output      = fa;
                configAllreadyDone = true;
            }
        }
Пример #11
0
        /// <summary>
        /// Initialises the stream logger.
        /// </summary>
        public void init()
        {
#if LOG_ON
            PatternLayout layout = new PatternLayout("%r [%t] %p %c %x - %m%n");
            StreamHandler writer = new StreamHandler(this);

            TextWriterAppender appender = new TextWriterAppender();
            appender.Layout = layout;
            appender.Writer = writer;

            Hierarchy h = LogManager.GetRepository() as Hierarchy;
            h.Root.AddAppender(appender);
#endif
        }
Пример #12
0
        static Log4netBenchmark()
        {
            LogProvider.SetCurrentLogProvider(new Log4NetLogProvider());

            var logInjectionSettings = new TracerSettings
            {
                StartupDiagnosticLogEnabled = false,
                LogsInjectionEnabled        = true,
                Environment    = "env",
                ServiceVersion = "version"
            };

            LogInjectionTracer = new Tracer(logInjectionSettings, new DummyAgentWriter(), null, null, null);
            Tracer.Instance    = LogInjectionTracer;

            var baselineSettings = new TracerSettings
            {
                StartupDiagnosticLogEnabled = false,
                LogsInjectionEnabled        = false,
                Environment    = "env",
                ServiceVersion = "version"
            };

            BaselineTracer = new Tracer(baselineSettings, new DummyAgentWriter(), null, null, null);

            var repository    = (Hierarchy)log4net.LogManager.GetRepository();
            var patternLayout = new PatternLayout {
                ConversionPattern = "%date [%thread] %-5level %logger {dd.env=%property{dd.env}, dd.service=%property{dd.service}, dd.version=%property{dd.version}, dd.trace_id=%property{dd.trace_id}, dd.span_id=%property{dd.span_id}} - %message%newline"
            };

            patternLayout.ActivateOptions();

#if DEBUG
            var writer = System.Console.Out;
#else
            var writer = TextWriter.Null;
#endif

            var appender = new TextWriterAppender {
                Layout = patternLayout, Writer = writer
            };

            repository.Root.AddAppender(appender);

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

            Logger = log4net.LogManager.GetLogger(typeof(Log4netBenchmark));
        }
Пример #13
0
        private long GetLog4NetTimestamp(DateTime dateTime)
        {
            var logXmlBuilder = new StringBuilder();

            using (var writer = new StringWriter(logXmlBuilder))
            {
                var layout   = new XmlLayoutSchemaLog4j();
                var appender = new TextWriterAppender
                {
                    ImmediateFlush = true,
                    Layout         = layout,
                    Writer         = writer
                };
                var repository = LogManager.GetRepository(Assembly.GetCallingAssembly());

                var eventData = new LoggingEventData
                {
                    LoggerName   = "TestLogger",
                    TimeStampUtc = dateTime.ToUniversalTime(),
                    Level        = log4net.Core.Level.Debug,
                    ThreadName   = "TestThread",
                    Message      = "Test message."
                };
                var @event = new LoggingEvent(typeof(TimestampTests), repository, eventData);
                appender.DoAppend(@event);

                writer.Flush();

                appender.Close();
            }

            var logXml = logXmlBuilder.ToString();

            const string timestampStartMarker = "timestamp=\"";
            var          timestampStart       = logXml.IndexOf(timestampStartMarker) + timestampStartMarker.Length;

            Assume.That(timestampStart, Is.GreaterThanOrEqualTo(0));
            var timestampEnd = logXml.IndexOf('"', timestampStart);

            Assume.That(timestampEnd, Is.GreaterThanOrEqualTo(0));

            var timestampString = logXml.Substring(timestampStart, timestampEnd - timestampStart);

            var timestamp = Int64.Parse(timestampString);

            return(timestamp);
        }
Пример #14
0
        public void TestSetup()
        {
            outputBuilder = new StringBuilder();
            outputWriter = new StringWriter(outputBuilder);

            memoryAppender = new MemoryAppender();
            textAppender = new TextWriterAppender {Writer = outputWriter, Layout = new PatternLayout("%m")};

            log4netRepository = LogManager.GetAllRepositories().SingleOrDefault(x => x.Name == "test") ?? LogManager.CreateRepository("test");
            log4netRepository.ResetConfiguration();

            BasicConfigurator.Configure(log4netRepository, memoryAppender, textAppender);

            log4netLogger = LogManager.GetLogger("test", "root").Logger;

            adapter = new Log4netLog(log4netLogger);
        }
Пример #15
0
        // ------------------------------------------------------------------------------------

        private void _BeginStoreLogMessages()
        {
            logMessages         = new StringBuilder(8192);
            appenderLogMessages = new TextWriterAppender();
            appenderLogMessages.ImmediateFlush = true;
            appenderLogMessages.Layout         = new log4net.Layout.PatternLayout("%date %-5level %message%newline");
            appenderLogMessages.Writer         = new StringWriter(logMessages);

            appenderLogMessages.Threshold = Level.Info;

            IAppenderAttachable appender_attachable = log.Logger as IAppenderAttachable;

            if (appender_attachable != null)
            {
                appender_attachable.AddAppender(appenderLogMessages);
            }

            appenderLogMessages.ActivateOptions();
        }