Log() public method

public Log ( LogLevel, logLevel, EventId, eventId, state, Exception, exception, Func, formatter ) : void
logLevel LogLevel,
eventId EventId,
exception Exception,
formatter Func,
return void
        public void BeginScope_Should_Include_CustomScopeState_In_LoggedMessage()
        {
            const string CustomScope = "CustomScope";

            var mockedFactory = new Mock <ILog4NetScopeFactory>(MockBehavior.Default);

            mockedFactory.Setup(x => x.BeginScope(It.IsAny <string>()))
            .Returns(new Log4NetScope(CustomScope, new Log4NetScopeRegistry()));

            var options = ConfigureOptions(Log4NetFileOption.TestAppenderTrace);

            options.ScopeFactory = mockedFactory.Object;
            var testAppender = GetTestAppender(options);

            var sut = new Log4NetLogger(options);

            using (var scope = sut.BeginScope(CustomScope))
            {
                sut.Log(LogLevel.Critical, _eventId, _logState, null, (message, exception) => message);
            }

            sut.Log(LogLevel.Critical, _eventId, _logState, null, (message, exception) => message);

            // https://stackoverflow.com/questions/14438217/memoryappender-patternlayout-not-rendering
            testAppender.GetEvents()
            .Should()
            .NotBeEmpty()
            .And
            .HaveCount(2);
            testAppender.GetEvents()
            .First()
            .Level
            .Should()
            .Be(Level.Fatal);
            var textWriter = new StringWriter();

            testAppender.Layout.Format(textWriter, testAppender.GetEvents().First());
            textWriter.ToString()
            .Should()
            .Contain(_logState);
            textWriter.ToString()
            .Should()
            .Contain(CustomScope);

            textWriter.Close();
            textWriter = new StringWriter();
            testAppender.Layout.Format(textWriter, testAppender.GetEvents().Last());
            textWriter.ToString()
            .Should()
            .NotContain(CustomScope);
        }
        public void Log_Should_AddMessageAsCritical_When_LogException()
        {
            var options = ConfigureOptions(Log4NetFileOption.TestAppenderTrace);

            options.OverrideCriticalLevelWith = "Critical";

            var testAppender = GetTestAppender(options);

            var sut = new Log4NetLogger(options);

            sut.Log(LogLevel.Critical, _eventId, string.Empty, new ArgumentNullException(nameof(sut)), (message, exception) => exception.Message);

            testAppender.GetEvents()
            .Should()
            .NotBeEmpty()
            .And
            .ContainSingle();
            testAppender.GetEvents()
            .First().Level
            .Should()
            .Be(Level.Critical);
            testAppender.GetEvents()
            .First()
            .RenderedMessage
            .Should()
            .Contain("sut");
        }
Ejemplo n.º 3
0
        public byte[] Download(RestRequest request)
        {
            var client = new RestClient
            {
                BaseUrl         = new System.Uri(BaseUrl),
                CookieContainer = _cookieContainer
            };
            var response = client.Execute(request);

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response.  Check inner details for more info.";
                //var twilioException = new ApplicationException(message, response.ErrorException);
                Logger.Log($"请求[{request.Resource}]时,{message}", Category.Exception, Priority.High);
                //throw twilioException;
            }

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var cookie = response.Cookies.FirstOrDefault();
                if (cookie != null)
                {
                    CookieContainer cookiecon = new CookieContainer();
                    cookiecon.Add(new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain));
                    SetCookieContainer(cookiecon);
                }
            }


            return(response.RawBytes);
        }
        public void Log_Should_AddMessage_With_ExpectedLevel(LogLevel logLevel, Level eventLevel)
        {
            var options      = ConfigureOptions(Log4NetFileOption.TestAppenderTrace);
            var testAppender = GetTestAppender(options);

            var sut = new Log4NetLogger(options);

            sut.Log(logLevel, _eventId, _logState, null, (message, exception) => message);

            testAppender.GetEvents()
            .Should()
            .NotBeEmpty()
            .And
            .ContainSingle();
            testAppender.GetEvents()
            .First()
            .Level
            .Should()
            .Be(eventLevel);
            testAppender.GetEvents()
            .First()
            .RenderedMessage
            .Should()
            .Contain(_logState);
        }
        public void Log_Should_AddMessageAsCritical_When_LogLevelCritical_And_OverrideCriticalLevelWithIsSet()
        {
            var options = ConfigureOptions(Log4NetFileOption.TestAppenderTrace);

            options.OverrideCriticalLevelWith = "Critical";

            var testAppender = GetTestAppender(options);

            var sut = new Log4NetLogger(options);

            sut.Log(LogLevel.Critical, _eventId, _logState, null, (message, exception) => message);

            testAppender.GetEvents()
            .Should()
            .NotBeEmpty()
            .And
            .ContainSingle();
            testAppender.GetEvents()
            .First()
            .Level
            .Should()
            .Be(Level.Critical);
            testAppender.GetEvents()
            .First().RenderedMessage
            .Should()
            .Contain(_logState);
        }
        public void Log_Should_Emit_LoggingEvents_Created_By_Custom_LoggingEventFactory()
        {
            var options = ConfigureOptions(Log4NetFileOption.TestAppenderTrace);

            var callStackBoundary      = typeof(Log4NetLoggerTests);
            var expectedRepository     = log4net.LogManager.GetRepository(options.LoggerRepository);
            var expectedLoggerName     = "testLogger";
            var expectedLoggingLevel   = Level.Info;
            var expectedLoggingMessage = "testMessage";
            var expectedException      = new InvalidOperationException("testException");

            var mockedFactory = new Mock <ILog4NetLoggingEventFactory>();

            mockedFactory
            .Setup(
                f => f.CreateLoggingEvent(It.IsAny <MessageCandidate <string> >(), It.IsAny <log4net.Core.ILogger>(), options)
                )
            .Returns(
                new LoggingEvent(
                    callStackBoundary,
                    expectedRepository,
                    expectedLoggerName,
                    expectedLoggingLevel,
                    expectedLoggingMessage,
                    expectedException
                    )
                );

            options.LoggingEventFactory = mockedFactory.Object;
            var testAppender = GetTestAppender(options);
            var sut          = new Log4NetLogger(options);

            sut.Log(LogLevel.Debug, _eventId, _logState, null, (message, exception) => message);

            testAppender.GetEvents()
            .Should()
            .NotBeEmpty()
            .And
            .HaveCount(1);

            var loggingEvent = testAppender.GetEvents()
                               .First();

            loggingEvent.Repository
            .Should()
            .Be(expectedRepository);
            loggingEvent.LoggerName
            .Should()
            .Be(expectedLoggerName);
            loggingEvent.Level
            .Should()
            .Be(expectedLoggingLevel);
            loggingEvent.MessageObject
            .Should()
            .Be(expectedLoggingMessage);
            loggingEvent.ExceptionObject
            .Should()
            .Be(expectedException);
        }
        public void Log_Should_Emit_At_LogLevels_Translate_By_LogLevelTranslator()
        {
            var options = ConfigureOptions(Log4NetFileOption.TestAppenderTrace);

            var expectedWarningLevel = new Level(100000, "Custom Level");
            var expectedErrorLevel   = Level.Emergency;

            var mockedTranslator = new Mock <ILog4NetLogLevelTranslator>();

            mockedTranslator
            .Setup(
                f => f.TranslateLogLevel(LogLevel.Warning, options)
                )
            .Returns(expectedWarningLevel);

            mockedTranslator.Setup(
                f => f.TranslateLogLevel(LogLevel.Error, options)
                )
            .Returns(expectedErrorLevel);


            options.LogLevelTranslator = mockedTranslator.Object;
            var testAppender = GetTestAppender(options);
            var sut          = new Log4NetLogger(options);

            sut.Log(LogLevel.Warning, _eventId, _logState, null, (message, exception) => message);
            sut.Log(LogLevel.Error, _eventId, _logState, null, (message, exception) => message);

            testAppender.GetEvents()
            .Should()
            .NotBeEmpty()
            .And
            .HaveCount(2);

            testAppender.GetEvents()
            .First()
            .Level
            .Should()
            .Be(expectedWarningLevel);

            testAppender.GetEvents()
            .ElementAt(1)
            .Level
            .Should()
            .Be(expectedErrorLevel);
        }
        public void Log_Should_Throw_When_FormaterIsInvalid()
        {
            var options      = ConfigureOptions(Log4NetFileOption.TestAppenderTrace);
            var testAppender = GetTestAppender(options);

            var sut = new Log4NetLogger(options);

            Assert.Throws <ArgumentNullException>(() => sut.Log(LogLevel.Information, _eventId, _logState, null, null));
        }
        public void Log_Should_Throw_When_LogLevelIsNotValid()
        {
            var options      = ConfigureOptions(Log4NetFileOption.TestAppenderTrace);
            var testAppender = GetTestAppender(options);

            var sut = new Log4NetLogger(options);

            Assert.Throws <ArgumentOutOfRangeException>(() => sut.Log((LogLevel)52, _eventId, _logState, null, (message, exception) => message));
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            var logfile = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "log4net.config");

            Log4NetLogger.Init(logfile);
            Log4NetLogger k = new Log4NetLogger();

            k.Log("this is a debug log...", LogType.Debug);
            Console.ReadLine();
        }
Ejemplo n.º 11
0
        public void CanWriteToLoggerInWarnCategory()
        {
            ILoggerFacade logger = new Log4NetLogger();

            logger.Log("Test", Category.Warn, Priority.Low);

            string output = appender.GetString();
            StringAssert.Contains(output, "Test");
            StringAssert.Contains(output, "WARN");
        }
Ejemplo n.º 12
0
        public void CanWriteToLoggerInErrorCategory()
        {
            ILoggerFacade logger = new Log4NetLogger();

            logger.Log("Test", Category.Exception, Priority.Low);

            string output = appender.GetString();
            StringAssert.Contains(output, "Test");
            StringAssert.Contains(output, "ERROR");
        }
        public void Log_Should_IgnoreMessage_With_LevelNone()
        {
            var options      = ConfigureOptions(Log4NetFileOption.TestAppenderTrace);
            var testAppender = GetTestAppender(options);

            var sut = new Log4NetLogger(options);

            sut.Log(LogLevel.None, _eventId, _logState, null, (message, exception) => message);

            testAppender.GetEvents()
            .Should()
            .BeEmpty();
        }
        public void Log_Should_Not_IgnoreMessage_When_Empty_For_Non_Null_Exception()
        {
            Log4NetProviderOptions options = ConfigureOptions(Log4NetFileOption.TestAppenderTrace);
            var testAppender = GetTestAppender(options);

            var sut = new Log4NetLogger(options);

            sut.Log(LogLevel.Trace, _eventId, string.Empty, new Exception("Something went wrong"), (message, exception) => message);

            testAppender.GetEvents()
            .Should()
            .NotBeEmpty();
        }
        public void Log_Should_IgnoreMessage_When_Empty()
        {
            Log4NetProviderOptions options = ConfigureOptions(Log4NetFileOption.TestAppenderTrace);
            var testAppender = GetTestAppender(options);

            var sut = new Log4NetLogger(options);

            sut.Log(LogLevel.Trace, _eventId, string.Empty, null, (message, exception) => message);

            testAppender.GetEvents()
            .Should()
            .BeEmpty();
        }
        public void log_with_calls_info_calls_the_correct_loglevel_method()
        {
            // Arrange
            var logger = new Log4NetLogger("TestLogger")
            {
                Logger = GetFakeLogger()
            };

            // Act
            logger.Log(LogLevel.Information, new EventId(), "Info log", null, null);

            // Assert
            logger.Logger.Received(1).Info("Info log", null);
        }
        public void log_with_calls_fatal_calls_the_correct_loglevel_method()
        {
            // Arrange
            var logger = new Log4NetLogger("TestLogger")
            {
                Logger = GetFakeLogger()
            };

            // Act
            logger.Log(LogLevel.Critical, new EventId(), "Fatal log", null, null);

            // Assert
            logger.Logger.Received(1).Fatal("Fatal log", null);
        }
        public void log_with_calls_invalid_level_does_not_call_fatal()
        {
            // Arrange
            var logger = new Log4NetLogger("TestLogger")
            {
                Logger = GetFakeLogger()
            };

            // Act
            logger.Log((LogLevel)99, new EventId(), "Invalid log", null, null);

            // Assert
            logger.Logger.DidNotReceive().Fatal("Invalid log", null);
        }
        public void log_with_calls_error_calls_the_correct_loglevel_method()
        {
            // Arrange
            var logger = new Log4NetLogger("TestLogger")
            {
                Logger = GetFakeLogger()
            };

            // Act
            logger.Log(LogLevel.Error, new EventId(), "Error log", null, null);

            // Assert
            logger.Logger.Received(1).Error("Error log", null);
        }
Ejemplo n.º 20
0
        public bool Execute(RestRequest request)
        {
            var result = false;

            try
            {
                var client = new RestClient
                {
                    BaseUrl         = new System.Uri(BaseUrl),
                    CookieContainer = _cookieContainer
                };
                var response = client.Execute(request);

                if (response.ErrorException != null)
                {
                    const string message         = "Error retrieving response.  Check inner details for more info.";
                    var          twilioException = new ApplicationException(message, response.ErrorException);
                    Logger?.Log($"请求[{request.Resource}]时,{message}", Category.Exception, Priority.High);
                    //throw twilioException;
                }

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var cookie = response.Cookies.FirstOrDefault();
                    if (cookie != null)
                    {
                        CookieContainer cookiecon = new CookieContainer();
                        cookiecon.Add(new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain));
                        SetCookieContainer(cookiecon);
                    }
                }


                var resultObject = JsonConvert.DeserializeObject(response.Content) as JObject;
                if (resultObject != null)
                {
                    var responseCode = resultObject.Property("errorCode").Value.Value <int>();
                    if (ResultTable.ContainsKey(responseCode))
                    {
                        Logger?.Log($"[{request.Resource}]~[{ResultTable[responseCode]}]", Category.Info, Priority.Medium);
                    }
                    else
                    {
                        Logger?.Log($"[{request.Resource}]~[{responseCode}]", Category.Info, Priority.Medium);
                    }
                    if (responseCode != 0)
                    {
                        result = false;
                    }
                    else
                    {
                        result = true;
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                Logger?.Log($"请求[{request.Resource}]时,发生错误:{ex.Message}", Category.Exception, Priority.High);
                return(result);
            }
        }