public void WhenALoggerWritesToTheSinkItIsRetrievableFromTheTableWithProperties()
		{
			var storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
			var tableClient = storageAccount.CreateCloudTableClient();
			var table = tableClient.GetTableReference("LogEventEntity");

			table.DeleteIfExists();

			var logger = new LoggerConfiguration()
				.WriteTo.AzureTableStorageWithProperties(storageAccount)
				.CreateLogger();

			var exception = new ArgumentException("Some exception");

			const string messageTemplate = "{Properties} should go in their {Numbered} {Space}";

			logger.Information(exception, messageTemplate, "Properties", 1234, ' ');

			var result = table.ExecuteQuery(new TableQuery().Take(1)).First();
			
			// Check the presence of same properties as in previous version
			Assert.AreEqual(messageTemplate, result.Properties["MessageTemplate"].StringValue);
			Assert.AreEqual("Information", result.Properties["Level"].StringValue);
			Assert.AreEqual("System.ArgumentException: Some exception", result.Properties["Exception"].StringValue);
			Assert.AreEqual("\"Properties\" should go in their 1234  ", result.Properties["RenderedMessage"].StringValue);

			// Check the presence of the new properties.
			Assert.AreEqual("Properties", result.Properties["Properties"].PropertyAsObject);
			Assert.AreEqual(1234, result.Properties["Numbered"].PropertyAsObject);
			Assert.AreEqual(" ", result.Properties["Space"].PropertyAsObject);
		}
Esempio n. 2
0
        public void EventsCanBeExcludedByPredicate()
        {
            var seen = 0;

            var log = new LoggerConfiguration()
                .Filter.ByExcluding(Matching.WithProperty<int>("Count", p => p < 10))
                .WriteTo.Sink(new DelegatingSink(e => seen++))
                .CreateLogger();

            log.Warning("Unrelated");
            log.Information("{Count}", 5);
            log.Information("{Count}", "wrong type");
            log.Information("{Count}", 15);

            Assert.Equal(3, seen);
        }
        public void AttributesAreConsultedWhenDestructuring()
        {
            LogEvent evt = null;

            var log = new LoggerConfiguration()
                .Destructure.UsingAttributes()
                .WriteTo.Sink(new DelegatingSink(e => evt = e))
                .CreateLogger();

            var customized = new Customized
            {
                ImmutableScalar = new ImmutableScalar(),
                MutableScalar = new MutableScalar(),
                NotAScalar = new NotAScalar(),
                Ignored = "Hello, there",
                ScalarAnyway = new NotAScalar()
            };

            log.Information("Here is {@Customized}", customized);

            var sv = (StructureValue)evt.Properties["Customized"];
            var props = sv.Properties.ToDictionary(p => p.Name, p => p.Value);

            Assert.IsInstanceOf<ImmutableScalar>(props["ImmutableScalar"].LiteralValue());
            Assert.AreEqual(new MutableScalar().ToString(), props["MutableScalar"].LiteralValue());
            Assert.IsInstanceOf<StructureValue>(props["NotAScalar"]);
            Assert.IsFalse(props.ContainsKey("Ignored"));
            Assert.IsInstanceOf<NotAScalar>(props["ScalarAnyway"].LiteralValue());
        }
        public void UsingSuperLongLogMessageWorks()
        {
            var charcounts = new[]
            {
                10*1000,
                20*1000,
                30*1000,
                40*1000,
                70*1000
            };
            foreach (var charcount in charcounts)
            {
                var log = new LoggerConfiguration()
                    .WriteTo.EventLog("EventLogSinkTests")
                    .CreateLogger();

                var guid = Guid.NewGuid().ToString("D");
                log.Information("This is a super long message which might be trimmed. Guid is {Guid}.The following text has {charcount} chars: {LongText}"
                    , guid
                    , charcount
                    , new string('x', charcount));

                Assert.IsTrue(EventLogMessageWithSpecificBodyExists(guid), "The message was not found in the eventlog. Charcount was " + charcount);
            }
        }
Esempio n. 5
0
        public void LoggingLevelSwitchDynamicallyChangesLevel()
        {
            var events = new List<LogEvent>();
            var sink = new DelegatingSink(events.Add);

            var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);

            var log = new LoggerConfiguration()
                .MinimumLevel.ControlledBy(levelSwitch)
                .WriteTo.Sink(sink)
                .CreateLogger()
                .ForContext<LoggerTests>();

            log.Debug("Suppressed");
            log.Information("Emitted");
            log.Warning("Emitted");

            // Change the level
            levelSwitch.MinimumLevel = LogEventLevel.Error;

            log.Warning("Suppressed");
            log.Error("Emitted");
            log.Fatal("Emitted");

            Assert.Equal(4, events.Count);
            Assert.True(events.All(evt => evt.RenderMessage() == "Emitted"));
        }
        public void LoggerTest()
        {
            var logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.WebRequest(new Uri(Url))
                .CreateLogger();

            logger.Information("Hello World");
        }
        public void UsingSpecialCharsWorks()
        {
            var log = new LoggerConfiguration()
                .WriteTo.EventLog("EventLogSinkTests")
                .CreateLogger();

            var guid = Guid.NewGuid().ToString("D");
            log.Information("This is a mesage with a {Guid} and a special char {char}", guid, "%1");

            Assert.IsTrue(EventLogMessageWithSpecificBodyExists(guid), "The message was not found in the eventlog.");
        }
Esempio n. 8
0
 static void Main()
 {
     const int iterations = 1000000;
     var log = new LoggerConfiguration()
         .WriteTo.File("test-" + Guid.NewGuid() + ".log")
         .CreateLogger();
     for (var i = 0; i < iterations; i++)
     {
         log.Information("Running iteration {I:00.0} for {@J}!", i, new { Goal = "Speed" });
     }
 }
        public void UsingAngleBracketsInSourceWorks()
        {
            var log = new LoggerConfiguration()
                .WriteTo.EventLog("EventLogSink<Tests>")
                .CreateLogger();

            var guid = Guid.NewGuid().ToString("D");
            log.Information("This is a normal mesage with a {Guid}", guid);

            Assert.IsTrue(EventLogMessageWithSpecificBodyExists(guid),
                "The message was not found in the eventlog.");
        }
        public void EnvironmentUserNameEnricherIsApplied()
        {
            LogEvent evt = null;
            var log = new LoggerConfiguration()
                .Enrich.WithEnvironmentUserName()
                .WriteTo.Sink(new DelegatingSink(e => evt = e))
                .CreateLogger();

            log.Information(@"Has an EnvironmentUserName property with [domain\]userName");

            Assert.IsNotNull(evt);
            Assert.IsNotNullOrEmpty((string)evt.Properties["EnvironmentUserName"].LiteralValue());
        }
Esempio n. 11
0
    public void SameGroupLabelsShouldBeInTheSameStreams()
    {
        var logger = new LoggerConfiguration()
                     .WriteTo.GrafanaLoki(
            "https://loki:3100",
            httpClient: _client)
                     .CreateLogger();

        logger.Information("This is an information without params");
        logger.Information("This is also an information without params");
        logger.Dispose();

        _client.Content.ShouldMatchApproved(
            c =>
        {
            c.SubFolder(ApprovalsFolderName);
            c.WithScrubber(
                s => Regex.Replace(
                    s,
                    TimeStampRegEx,
                    TimeStampReplacement));
        });
    }
Esempio n. 12
0
        public void SinkRespectsConfiguredMinimumErrorLevel()
        {
            var nIssues = 0;

            using (var sut = new LoggerConfiguration()
                             .WriteTo.YouTrack(new DummyReporter((s, s1, arg3, arg4) => nIssues += 1), c =>
                                               c.UseProject("abc"), restrictedToMinimumLevel: LogEventLevel.Error).CreateLogger())
            {
                sut.Information(new Exception(""), "fatal");
                sut.Error(new Exception(""), "nonfatal");
            }

            Assert.Equal(1, nIssues);
        }
Esempio n. 13
0
        public void ExpressionsControlConditionalSinks()
        {
            var sink   = new CollectingSink();
            var logger = new LoggerConfiguration()
                         .WriteTo.Conditional("A = 1 or A = 2", wt => wt.Sink(sink))
                         .CreateLogger();

            foreach (var a in Enumerable.Range(0, 5))
            {
                logger.Information("{A}", a);
            }

            Assert.Equal(2, sink.Events.Count);
        }
Esempio n. 14
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .CreateLogger();

            Log.Logger = logger;
            loggerFactory.AddSerilog();

            logger.Information("Logger configurado");
            logger.Information("MVC Configurado");

            app.UseStaticFiles();

            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}");
            });
        }
Esempio n. 15
0
        public Order createCart(int userId)
        {
            using var log = new LoggerConfiguration()
                            .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, shared: true)
                            .CreateLogger();
            log.Information($"DATALAYER DATABASE Created cart for (userId {userId}) (Changes not saved until item is added");
            Order cart = new Order();

            cart.UserId            = userId;
            cart.CheckoutTimestamp = null;
            cart.orderItems        = new List <OrderItem>();
            ctx.Orders.Add(cart);
            return(cart);
        }
        public void ThreadIdEnricherIsApplied()
        {
            LogEvent evt = null;
            var      log = new LoggerConfiguration()
                           .ReadFrom.AppSettings(filePath: GetConfigPath())
                           .WriteTo.Sink(new DelegatingSink(e => evt = e))
                           .CreateLogger();

            log.Information("Has a ThreadId property with value generated by ThreadIdEnricher");

            Assert.NotNull(evt);
            Assert.NotNull(evt.Properties["ThreadId"]);
            Assert.NotNull(evt.Properties["ThreadId"].LiteralValue() as int?);
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            var log = new LoggerConfiguration()
                      .WriteTo.Console()
                      .WriteTo.Http("http://*****:*****@customer} registered", customer);
                Thread.Sleep(1000);
            }
        }
        public void EmittingJsonFormattedEventsFromAppSettingsWorks()
        {
            var log = new LoggerConfiguration()
                      .ReadFrom.AppSettings()
                      .CreateLogger();

            var message = $"This is a JSON message with a {Guid.NewGuid():D}";

            log.Information(message);
            var messageFromLogEvent = EventLogMessageWithSpecificBody(message);

            Assert.IsNotNull(messageFromLogEvent, "The message was not found in the eventlog.");
            AssertJsonCarriesMessageTemplate(messageFromLogEvent, message);
        }
Esempio n. 19
0
        public void EventsAreWrittenToTheTextWriter()
        {
            var sw = new StringWriter();

            var log = new LoggerConfiguration()
                .WriteTo.TextWriter(sw)
                .CreateLogger();

            var mt = Some.String();
            log.Information(mt);

            var s = sw.ToString();
            Assert.That(s.Contains(mt));
        }
Esempio n. 20
0
        public void Run()
        {
            Console.WriteLine("Welcome from startup..");

            var logDirectory = _config.GetValue <string>("Runtime:LogOutputDirectory");
            // Using serilog here, can be anything
            var log = new LoggerConfiguration()
                      .WriteTo.Console()
                      .WriteTo.File(logDirectory)
                      .CreateLogger();

            log.Information("Serilog logger information");
            Console.WriteLine("Hello from App.cs");
        }
Esempio n. 21
0
        static void Main(string[] args)
        {
            // logger configuration reads from appsettings.json
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json")
                                .Build();

            var logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(configuration)
                         .CreateLogger();

            logger.Information("This should not log since restrictedToMinimumLevel is Error in appsettings.json!");
            logger.Error("Hello!");
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            var levelSwitch = new LoggingLevelSwitch();

            levelSwitch.MinimumLevel = LogEventLevel.Debug;

            Logger log = new LoggerConfiguration()
                         .WriteTo.File($"log_{DateTime.Now.ToString("dd_MM__hh_mm_ss")}.txt")
                         .MinimumLevel.ControlledBy(levelSwitch)
                         .CreateLogger();

            log.Debug("Come bag");
            log.Information($"{DateTime.Now.ToString()}");
            log.Error($"{new ArgumentException().ToString()}");

            levelSwitch.MinimumLevel = LogEventLevel.Error;

            log.Debug("Come bag");
            log.Information($"{DateTime.Now.ToString()}");
            log.Error($"{new ArgumentException().ToString()}");

            Console.WriteLine("Serilog test");
        }
        public void EnvironmentVariableExpansionIsApplied()
        {
            LogEvent evt = null;
            var      log = new LoggerConfiguration()
                           .ReadFrom.AppSettings(filePath: GetConfigPath())
                           .WriteTo.Sink(new DelegatingSink(e => evt = e))
                           .CreateLogger();

            log.Information("Has a Path property with value expanded from the environment variable");

            Assert.NotNull(evt);
            Assert.NotEmpty((string)evt.Properties["Path"].LiteralValue());
            Assert.NotEqual("%PATH%", evt.Properties["Path"].LiteralValue());
        }
Esempio n. 24
0
        public void Type_is_taken_from_environment_variables()
        {
            Environment.SetEnvironmentVariable("WEBJOBS_TYPE", "Continious");

            LogEvent logEvent = null;
            var      logger   = new LoggerConfiguration()
                                .Enrich.With(new AzureWebJobsTypeEnricher())
                                .WriteTo.Sink(new DelegatingSink(e => logEvent = e))
                                .CreateLogger();

            logger.Information("Test log");

            Assert.AreEqual("Continious", ((ScalarValue)logEvent.Properties["AzureWebJobsType"]).Value);
        }
Esempio n. 25
0
        private static ILogger ConfigureLogger()
        {
            var logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .WriteTo.File(
                "logs/logs.log",
                rollingInterval: RollingInterval.Day,
                outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] [{Context}] {Message:lj}{NewLine}{Exception}")
                         .CreateLogger();

            logger.Information("Logger configured");

            return(logger);
        }
        public void EnrivonmentUserNameEnricherIsApplied()
        {
            LogEvent evt = null;
            var      log = new LoggerConfiguration()
                           .ReadFrom.AppSettings(filePath: GetConfigPath())
                           .WriteTo.Sink(new DelegatingSink(e => evt = e))
                           .CreateLogger();

            log.Information("Has a EnrivonmentUserName property with value generated by EnrivonmentUserNameEnricher");

            Assert.NotNull(evt);
            Assert.NotNull(evt.Properties["EnvironmentUserName"]);
            Assert.NotEmpty((string)evt.Properties["EnvironmentUserName"].LiteralValue());
        }
Esempio n. 27
0
        public void Login()
        {
            // Create Logger
            var log = new LoggerConfiguration()
                      .WriteTo.Console()
                      .WriteTo.File("logs/log.txt", rollOnFileSizeLimit: true, fileSizeLimitBytes: 10_000_000, retainedFileCountLimit: 3)
                      .CreateLogger();

            // Output logs
            log.Warning("This is a warning message");
            log.Information("This is an info message");
            log.Error("This is an error message");
            log.Fatal("This is a fatal message");
        }
Esempio n. 28
0
        public void TestGetLoggerBasedOnConfig()
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("AppSettings.json")
                                .Build();

            using (var logger = new LoggerConfiguration()
                                .ReadFrom.Configuration(configuration)
                                .CreateLogger())
            {
                logger.Information("Cool");
            }
        }
Esempio n. 29
0
        public bool IsCallable()
        {
            LogEvent lastEvent = null;

            var log = new LoggerConfiguration()
                      .WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
                      .Enrich.FromLogContext()
                      .CreateLogger();

            using (LogContext.PushProperty("Number", 42))
                log.Information("Hello");

            return(42.Equals(lastEvent.Properties["Number"].LiteralValue()));
        }
Esempio n. 30
0
        public void When_CurrentHttpContextIsNotNull_ShouldNot_CreateCorrelationIdProperty()
        {
            HttpContext.Current = null;
            LogEvent evt = null;
            var      log = new LoggerConfiguration()
                           .Enrich.WithCorrelationId()
                           .WriteTo.Sink(new DelegateSink.DelegatingSink(e => evt = e))
                           .CreateLogger();

            log.Information(@"Does not have a CorrelationId property");

            Assert.NotNull(evt);
            Assert.IsFalse(evt.Properties.ContainsKey("CorrelationId"));
        }
        public void When_environtment_variable_is_set_it_is_also_used()
        {
            Environment.SetEnvironmentVariable("WEBSITE_SITE_NAME", "AzureWebAppName");

            LogEvent logEvent = null;
            var      logger   = new LoggerConfiguration()
                                .Enrich.With(new AzureWebAppsNameEnricher("namename"))
                                .WriteTo.Sink(new DelegatingSink(e => logEvent = e))
                                .CreateLogger();

            logger.Information("Test log");

            Assert.AreEqual("AzureWebAppName", ((ScalarValue)logEvent.Properties["AzureWebAppsName"]).Value);
        }
Esempio n. 32
0
        public void EmittingJsonFormattedEventsWorks()
        {
            var log = new LoggerConfiguration()
                      .WriteTo.EventLog(new JsonFormatter(), EventLogSource, manageEventSource: true)
                      .CreateLogger();

            var message = $"This is a JSON message with a {Guid.NewGuid():D}";

            log.Information(message);
            var messageFromLogEvent = EventLogMessageWithSpecificBody(message);

            Assert.IsNotNull(messageFromLogEvent, "The message was not found in the eventlog.");
            AssertJsonCarriesMessageTemplate(messageFromLogEvent, message);
        }
Esempio n. 33
0
        public static void HelloLog()
        {
            // Create Logger
            var logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();

            // Output logs
            logger.Debug("Serilog Debugging message");
            logger.Information("Serilog Information message");
            logger.Warning("Serilog Warning message");
            logger.Error("Serilog Error message");
            logger.Fatal("Serilog Fatal message");
        }
Esempio n. 34
0
        public void UsingSuperLongSourceNamesAreCorrectlyTrimmed()
        {
            for (var i = 199; i < 270; i += 10)
            {
                var log = new LoggerConfiguration()
                          .WriteTo.EventLog(EventLogSource + new string('x', i - EventLogSource.Length), manageEventSource: true)
                          .CreateLogger();

                var guid = Guid.NewGuid().ToString("D");
                log.Information("This is a mesage with a {Guid}, source had length {length}", guid, i);

                Assert.IsTrue(EventLogMessageWithSpecificBodyExists(guid), "The message was not found in the eventlog. SourceLength was " + i);
            }
        }
Esempio n. 35
0
        private static void Example_Log_To_Console()
        {
            var log = new LoggerConfiguration()
                      .WriteTo.Console()
                      .CreateLogger();

            log.Information("Hello, Serilog!");

            Log.Logger = log;

            Log.Information("The global logger has been configured");

            Console.WriteLine("Hello World!");
        }
Esempio n. 36
0
        public void Can_Specify_Minimum_Severity()
        {
            var methodInfo = nameof(Can_Specify_Minimum_Severity);

            using (var log = new LoggerConfiguration()
                             .WriteTo.Loupe(restrictedToMinimumLevel: LogEventLevel.Information)
                             .CreateLogger())
            {
                log.Debug("This is a debug message about {methodInfo} and should NOT be displayed", methodInfo);
                log.Verbose("This is a verbose message about {methodInfo} and should NOT be displayed", methodInfo);
                log.Information("This is an informational message about {methodInfo} and SHOULD be displayed", methodInfo);
                log.Error("This is an error message about {methodInfo} and SHOULD be displayed", methodInfo);
            }
        }
Esempio n. 37
0
        public void PayTobinTax(float transactionValue, [FromBody] Guid shareProviderId)
        {
            var tobinTaxValue = transactionValue / 100;

            if (!Directory.Exists("C:\\TSEIS\\"))
            {
                Directory.CreateDirectory("C:\\TSEIS\\");
            }

            using (var log = new LoggerConfiguration().WriteTo.File("C:\\TSEIS\\tobinTaxLog.txt").CreateLogger())
            {
                log.Information($"Transaction: {shareProviderId} has been taxed {tobinTaxValue.ToString(CultureInfo.InvariantCulture)}(1%) of the total value.");
            }
        }
Esempio n. 38
0
        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            var stacktrace       = exception.StackTrace;
            var exceptionMessage = exception.Message;
            var log = new LoggerConfiguration()
                      .WriteTo.File("log.txt", outputTemplate: "{NewLine}[{Timestamp:HH:mm:ss}{Level:u3}]{Message}{NewLine}{Exception}{NewLine}-------------{NewLine}")
                      .CreateLogger();

            log.Information($"{exceptionMessage}\r\n{stacktrace}");

            //await _emailSender.SendEmailAsync(_emailSetting.Value.SysAdminEmail, stacktrace, EmailType.SystemLog);
        }
Esempio n. 39
0
        public void AnExceptionThrownByAnEnricherIsNotPropagated()
        {
            var thrown = false;

            var l = new LoggerConfiguration()
                .Enrich.With(new DelegatingEnricher((le, pf) => {
                    thrown = true;
                    throw new Exception("No go, pal."); }))
                .CreateLogger();

            l.Information(Some.String());

            Assert.IsTrue(thrown);
        }
Esempio n. 40
0
        static void Main(string[] args)
        {
            var log = new LoggerConfiguration()
                      .WriteTo.Console()
                      .WriteTo.Sample()
                      .CreateLogger();

            var position  = new { Latitude = 25, Longitude = 134 };
            var elapsedMs = 34;

            log.Information("Processed {@Position} in {Elapsed:000} ms.", position, elapsedMs);

            Console.WriteLine("Hello World!");
        }
Esempio n. 41
0
        public static async Task <HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter traceWriter)
        {
            var body = await req.Content.ReadAsStringAsync();

            var log = new LoggerConfiguration()
                      .WriteTo.RollingFile("log-{Date}.txt")
                      .WriteTo.TraceWriter(traceWriter)
                      .WriteTo.Stackify()
                      .CreateLogger();

            log.Information("serilog: " + body);

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Esempio n. 42
0
        public void ShouldKeepEvents()
        {
            var messagesQueue = new Queue <string>();

            var log = new LoggerConfiguration()
                      .WriteTo.MemoryWriter(messagesQueue, 2, outputTemplate: "{Message}")
                      .CreateLogger();

            log.Information("my test string");

            messagesQueue.ShouldNotBeEmpty();
            messagesQueue.Count.ShouldBe(1);
            messagesQueue.ToArray()[0].ShouldBe("my test string");
        }
Esempio n. 43
0
        public void EventsAreWrittenToTheTextWriterUsingFormatProvider()
        {
            var sw = new StringWriter();

            var french = CultureInfo.GetCultureInfo("fr-FR");
            var log = new LoggerConfiguration()
                .WriteTo.TextWriter(sw, formatProvider: french)
                .CreateLogger();

            var mt = String.Format(french, "{0}", 12.345);
            log.Information("{0}", 12.345);

            var s = sw.ToString();
            Assert.That(s.Contains(mt));
        }
        public void AdditionalHeadersTest()
        {
            var headers = new NameValueCollection();
            headers.Add("X-Test-Header", "Test Header Value");

            var logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.WebRequest(new Uri(glipWebhook), contentType: "application/json", headers: headers)
                .CreateLogger();

            var message = new GlipMessage();

            logger.Information("{{ \"icon\": {icon}, \"activity\": {activity}, \"title\": {title}, \"body\": {body} }}",
                message.Icon, message.Activity, message.Title, message.Body);
        }
        public void PropertyEnrichmentIsApplied()
        {
            LogEvent evt = null;
            var log = new LoggerConfiguration()
                .ReadFrom.KeyValuePairs(new Dictionary<string, string>
                {
                    {"enrich:with-property:App", "Test"}
                })
                .WriteTo.Sink(new DelegatingSink(e => evt = e))
                .CreateLogger();

            log.Information("Has a test property");

            Assert.IsNotNull(evt);
            Assert.AreEqual("Test", evt.Properties["App"].LiteralValue());
        }
        public void SpecifyingThatATypeIsScalarCausesItToBeLoggedAsScalarEvenWhenDestructuring()
        {
            var events = new List<LogEvent>();
            var sink = new DelegatingSink(events.Add);
            
            var logger = new LoggerConfiguration()
                .WriteTo.Sink(sink)
                .Destructure.AsScalar(typeof(AB))
                .CreateLogger();

            logger.Information("{@AB}", new AB());

            var ev = events.Single();
            var prop = ev.Properties["AB"];
            Assert.IsInstanceOf<ScalarValue>(prop);
        }
Esempio n. 47
0
        public void DestructuringSystemTypeGivesScalarByDefault()
        {
            var events = new List<LogEvent>();
            var sink = new DelegatingSink(events.Add);

            var logger = new LoggerConfiguration()
                .WriteTo.Sink(sink)
                .CreateLogger();

            var thisType = this.GetType();
            logger.Information("{@thisType}", thisType);

            var ev = events.Single();
            var prop = ev.Properties["thisType"];
            var sv = Assert.IsAssignableFrom<ScalarValue>(prop);
            Assert.Equal(thisType, sv.LiteralValue());
        }
Esempio n. 48
0
        public void EnvironmentVariableExpansionIsApplied()
        {
            // Make sure we have the expected key in the App.config
            Assert.AreEqual("%PATH%", ConfigurationManager.AppSettings["serilog:enrich:with-property:Path"]);

            LogEvent evt = null;
            var log = new LoggerConfiguration()
                .ReadFrom.AppSettings()
                .WriteTo.Sink(new DelegatingSink(e => evt = e))
                .CreateLogger();

            log.Information("Has a Path property with value expanded from the environment variable");

            Assert.IsNotNull(evt);
            Assert.IsNotNullOrEmpty((string)evt.Properties["Path"].LiteralValue());
            Assert.AreNotEqual("%PATH%", evt.Properties["Path"].LiteralValue());
        }
        public void Works()
        {
            var selfLogMessages = new List<string>();
            SelfLog.Enable(selfLogMessages.Add);

            var emailLogger = new LoggerConfiguration()
                .WriteTo.Email(
                    fromEmail: "*****@*****.**",
                    toEmail: "*****@*****.**",
                    mailServer: "localhost",
                    outputTemplate: "[{Level}] {Message}{NewLine}{Exception}",
                    mailSubject: "subject")
                .CreateLogger();

            emailLogger.Information("test {test}", "test");
            emailLogger.Dispose();

            Assert.Equal(Enumerable.Empty<string>(), selfLogMessages);
        }
Esempio n. 50
0
        public void DestructuringIsPossibleForSystemTypeDerivedProperties()
        {
            var events = new List<LogEvent>();
            var sink = new DelegatingSink(events.Add);

            var logger = new LoggerConfiguration()
                .Destructure.With(new ProjectedDestructuringPolicy(
                    canApply: t => typeof(Type).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()),
                    projection: o => ((Type)o).AssemblyQualifiedName))
                .WriteTo.Sink(sink)
                .CreateLogger();

            var thisType = this.GetType();
            logger.Information("{@thisType}", thisType);

            var ev = events.Single();
            var prop = ev.Properties["thisType"];
            var sv = Assert.IsAssignableFrom<ScalarValue>(prop);
            Assert.Equal(thisType.AssemblyQualifiedName, sv.LiteralValue());
        }
        public void TransformationsAreAppliedToEventProperties()
        {
            var events = new List<LogEvent>();
            var sink = new DelegatingSink(events.Add);

            var logger = new LoggerConfiguration()
                .WriteTo.Sink(sink)
                .Destructure.ByTransforming<AB>(ab => new { C = ab.B })
                .CreateLogger();

            logger.Information("{@AB}", new AB());

            var ev = events.Single();
            var prop = ev.Properties["AB"];
            var sv = (StructureValue)prop;
            var c = sv.Properties.Single();
            Assert.AreEqual("C", c.Name);
        }
Esempio n. 52
0
        public void ExceptionsThrownByPropertyAccessorsArePropagatedIfAuditingEnabled()
        {
            var logger = new LoggerConfiguration()
                .AuditTo.Sink(new CollectingSink())
                .CreateLogger();

            Assert.Throws<TargetInvocationException>(() => logger.Information("{@Value}", new ThrowingProperty()));
        }
Esempio n. 53
0
        public void ExceptionsThrownByPropertyAccessorsAreNotPropagated()
        {
            var logger = new LoggerConfiguration()
                .WriteTo.Sink(new CollectingSink())
                .CreateLogger();

            logger.Information("{@Value}", new ThrowingProperty());

            Assert.True(true, "No exception reached the caller");
        }
Esempio n. 54
0
        static void Main(string[] args)
        {
            var logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.ColoredConsole(
                    outputTemplate: "{Timestamp:HH:mm:ss} ({ThreadId}) [{Level}] {Message}{NewLine}{Exception}")
                .WriteTo.Trace()
                .WriteTo.NewRelic(applicationName: "Serilog.Sinks.NewRelic.Sample")
                .Enrich.With(new ThreadIdEnricher(), new MachineNameEnricher())
                .CreateLogger();

            logger.Information("This is a simple information message {Property1}",100);

            // Adding a custom transaction

            using (logger.BeginTimedOperation("Time a thread sleep for 2 seconds."))
            {
                Thread.Sleep(1000);
                using (logger.BeginTimedOperation("And inside we try a Task.Delay for 2 seconds."))
                {
                    Task.Delay(2000).Wait();
                }
                Thread.Sleep(1000);
            }

            using (logger.BeginTimedOperation("Using a passed in identifier", "test-loop"))
            {
                // ReSharper disable once NotAccessedVariable
                var a = "";
                for (var i = 0; i < 1000; i++)
                {
                    a += "b";
                }
            }

            // Exceed a limit
            using (logger.BeginTimedOperation("This should execute within 1 second.", null, LogEventLevel.Debug, TimeSpan.FromSeconds(1)))
            {
                Thread.Sleep(1100);
            }

            // Gauge

            var queue = new Queue<int>();
            var gauge = logger.GaugeOperation("queue", "item(s)", () => queue.Count());

            gauge.Write();

            queue.Enqueue(20);

            gauge.Write();

            queue.Dequeue();

            gauge.Write();

            // Counter
            var counter = logger.CountOperation("counter", "operation(s)", true, LogEventLevel.Debug, resolution: 2);
            counter.Increment();
            counter.Increment();
            counter.Increment();
            counter.Decrement();

            // Throw Exception
            try
            {
                throw new ApplicationException("This is an exception raised to test the New Relic API");
            }
            catch (Exception ex)
            {
               logger.Error(ex, "Error whilst testing the Serilog.Sinks.NewRelic.Sample");
            }

            System.Console.WriteLine("Press a key to exit.");
            System.Console.ReadKey(true);
        }
Esempio n. 55
0
        public void MaximumDestructuringDepthIsEffective()
        {
            var x = new { A = new { B = new { C = new { D = "F" } } } };

            LogEvent evt = null;
            var log = new LoggerConfiguration()
                .WriteTo.Sink(new DelegatingSink(e => evt = e))
                .Destructure.ToMaximumDepth(3)
                .CreateLogger();

            log.Information("{@X}", x);
            var xs = evt.Properties["X"].ToString();

            Assert.That(xs, Is.StringContaining("C"));
            Assert.That(xs, Is.Not.StringContaining("D"));
        }
Esempio n. 56
0
        public bool IsCallable()
        {
            var sw = new StringWriter();

            var log = new LoggerConfiguration()
                .WriteTo.TextWriter(sw, outputTemplate: "{Anything}{Number}")
                .Enrich.FromLogContext()
                .CreateLogger();

            using (LogContext.PushProperty("Number", 42))
                log.Information("Hello");

            var s = sw.ToString();
            return s == "42";
        }
Esempio n. 57
0
        public void ExceptionsThrownByDestructuringPoliciesArePropagatedIfAuditingEnabled()
        {
            var logger = new LoggerConfiguration()
                .AuditTo.Sink(new CollectingSink())
                .Destructure.ByTransforming<Value>(v => { throw new Exception("Boom!"); })
                .CreateLogger();

            Assert.Throws<Exception>(() => logger.Information("{@Value}", new Value()));
        }
        public void UsingSuperLongSourceNamesAreCorrectlyTrimmed()
        {
            for (var i = 199; i < 270; i+=10)
            {
                var log = new LoggerConfiguration()
                    .WriteTo.EventLog("EventLogSinkTests" + new string('x', i - "EventLogSinkTests".Length))
                    .CreateLogger();

                var guid = Guid.NewGuid().ToString("D");
                log.Information("This is a mesage with a {Guid}, source had length {length}", guid, i);

                Assert.IsTrue(EventLogMessageWithSpecificBodyExists(guid), "The message was not found in the eventlog. SourceLength was " + i);
            }
        }
Esempio n. 59
0
        public bool IsCallable()
        {
            LogEvent lastEvent = null;

            var log = new LoggerConfiguration()
                .WriteTo.Sink(new DelegatingSink(e => lastEvent = e))
                .Enrich.FromLogContext()
                .CreateLogger();

            using (LogContext.PushProperty("Number", 42))
                log.Information("Hello");

            return 42.Equals(lastEvent.Properties["Number"].LiteralValue());
        }
Esempio n. 60
0
        public void ExceptionsThrownByDestructuringPoliciesAreNotPropagated()
        {
            var logger = new LoggerConfiguration()
                .WriteTo.Sink(new CollectingSink())
                .Destructure.ByTransforming<Value>(v => { throw new Exception("Boom!"); })
                .CreateLogger();

            logger.Information("{@Value}", new Value());

            Assert.True(true, "No exception reached the caller");
        }