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);
        }
Example #2
0
        public void WhenInvalidApiKeyProvided_OnSinkSend_TraceAndSerilogSelfLogPopulated()
        {
            var serilogSelfLogWriter = new StringWriter();

            SelfLog.Enable(serilogSelfLogWriter);

            var traceWriter = new StringWriter();

            Trace.Listeners.Add(new TextWriterTraceListener(traceWriter));

            var logger = new LoggerConfiguration()
                         .WriteTo.LogglyBulk("!!FAKE KEY!!", new[] { "!!FAKE TAG!!" }).CreateLogger();

            logger.Fatal("!!FAKE MESSAGE!!");

            logger.Dispose();

            var traceResult = traceWriter.ToString();

            string.IsNullOrWhiteSpace(traceResult).Should().BeFalse();

            var selfLogResult = serilogSelfLogWriter.ToString();

            string.IsNullOrWhiteSpace(selfLogResult).Should().BeFalse();

            traceResult.Contains(
                "Exception posting to loggly System.Net.Http.HttpRequestException: Response status code does not indicate success")
            .Should()
            .BeTrue();

            selfLogResult.Contains(
                "Exception posting to loggly System.Net.Http.HttpRequestException: Response status code does not indicate success")
            .Should()
            .BeTrue();

            Console.WriteLine(traceResult);
            Console.WriteLine(selfLogResult);
        }
        /// <summary>
        /// Serilog에서 제공해준 서버에 올려보기
        /// https://getseq.net/Download 에서 다운
        /// </summary>
        internal void WritingLogServer()
        {
            var log = new LoggerConfiguration()
                      .Enrich.WithThreadId()           //ThreadID를 포함할 수 있다 Install-Package Serilog.Enrichers.Thread
                      .MinimumLevel.Debug()
                      .Enrich.WithProperty("Application", "Demo")
                      .WriteTo.Seq("http://localhost:5341")
                      .CreateLogger();

            var itemCount = 99;
            //for (var itemNumber = 0; itemNumber < itemCount; ++itemNumber)
            //    log.Debug("Processing item {ItemNumber} of {ItemCount}", itemNumber, itemCount);

            //중간에 기본적으로 적을 정보를 추가할 수 있다.
            var orderLog = log.ForContext("OrderId", 1);

            orderLog.Information("Looking up product codes");
            orderLog.Information("Product lookup took {Elapsed} ms", 1000);



            log.Dispose();
        }
Example #4
0
        public void NoLabelIsSet()
        {
            // Arrange
            var provider = new DefaultLogLabelProvider(new LokiLabel[0], new string[0]); // Explicitly NOT include level
            var log      = new LoggerConfiguration()
                           .MinimumLevel.Verbose()
                           .WriteTo.LokiHttp(() => new LokiSinkConfiguration
            {
                LokiUrl          = "http://test:80",
                LogLabelProvider = provider,
                HttpClient       = _client
            })
                           .CreateLogger();

            // Act
            log.Fatal("Fatal Level");
            log.Dispose();

            // Assert
            var response = JsonConvert.DeserializeObject <TestResponse>(_client.Content);

            response.Streams.First().Labels.ShouldBe("{}");
        }
Example #5
0
        public void GlobalLabelsCanBeSet()
        {
            var logLabels = new List <LokiLabel>
            {
                new LokiLabel("app", "demo"),
                new LokiLabel("namespace", "prod")
            };

            // Arrange
            var log = new LoggerConfiguration()
                      .MinimumLevel.Information()
                      .WriteTo.LokiHttp(_credentials, logLabels, _client)
                      .CreateLogger();

            // Act
            log.Error("Something's wrong");
            log.Dispose();

            // Assert
            var response = JsonConvert.DeserializeObject <TestResponse>(_client.Content);

            response.Streams.First().Labels.ShouldBe("{app=\"demo\",namespace=\"prod\",level=\"error\"}");
        }
Example #6
0
    public void LevelPropertyShouldBeRenamed()
    {
        var logger = new LoggerConfiguration()
                     .WriteTo.GrafanaLoki(
            "https://loki:3100",
            httpClient: _client)
                     .CreateLogger();

        // ReSharper disable once InconsistentLogPropertyNaming
        logger.Information("Hero's {level}", 42);
        logger.Dispose();

        _client.Content.ShouldMatchApproved(
            c =>
        {
            c.SubFolder(ApprovalsFolderName);
            c.WithScrubber(
                s => Regex.Replace(
                    s,
                    TimeStampRegEx,
                    TimeStampReplacement));
        });
    }
Example #7
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));
        });
    }
Example #8
0
    public void PropertyNameEqualToReservedKeywordShouldBeSanitized()
    {
        var logger = new LoggerConfiguration()
                     .WriteTo.GrafanaLoki(
            "https://loki:3100",
            textFormatter: new LokiJsonTextFormatter(),
            httpClient: _client)
                     .CreateLogger();

        logger.Information("This is {Message}", "Ukraine!");
        logger.Dispose();

        _client.Content.ShouldMatchApproved(
            c =>
        {
            c.SubFolder(ApprovalsFolderName);
            c.WithScrubber(
                s => Regex.Replace(
                    s,
                    TimeStampRegEx,
                    TimeStampReplacement));
        });
    }
        static void Main(string[] args)
        {
            // If something is wrong with our Serilog setup,
            // lets make sure we can see what the problem is.
            Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));
            Debugging.SelfLog.Enable(Console.Error);

            Console.WriteLine("Starting.");

            // NOTE: Please replace with your own settings.
            var settings = new InsightOpsSinkSettings
            {
                Region = "au", // au, eu, jp or us
                Token  = "<some guid from your account>",
                UseSsl = false
            };

            // Create our logger.
            var log = new LoggerConfiguration()
                      .MinimumLevel.Debug()
                      .WriteTo.InsightOps(settings)
                      .WriteTo.Console()
                      .CreateLogger();

            // Log some fake info.
            var position  = new { Latitude = 25, Longitude = 134 };
            var elapsedMs = 34;

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

            Console.WriteLine("Flushing and closing...");

            log.Dispose();

            Console.WriteLine("Finished.");
        }
Example #10
0
    public void ParameterAsLabelShouldGenerateNewGroupAndStream()
    {
        var logger = new LoggerConfiguration()
                     .WriteTo.GrafanaLoki(
            "https://loki:3100",
            propertiesAsLabels: new[] { "MeaningOfLife" },
            httpClient: _client)
                     .CreateLogger();

        logger.Information("What is the meaning of life?");
        logger.Information("The meaning of life is {MeaningOfLife}", 42);
        logger.Dispose();

        _client.Content.ShouldMatchApproved(
            c =>
        {
            c.SubFolder(ApprovalsFolderName);
            c.WithScrubber(
                s => Regex.Replace(
                    s,
                    TimeStampRegEx,
                    TimeStampReplacement));
        });
    }
Example #11
0
    public void PropertiesAsLabelsShouldBeCreatedCorrectly()
    {
        var logger = new LoggerConfiguration()
                     .WriteTo.GrafanaLoki(
            "https://loki:3100",
            propertiesAsLabels: new[] { "level" },
            textFormatter: new LokiJsonTextFormatter(),
            httpClient: _client)
                     .CreateLogger();

        logger.Information("This is {Country}", "Ukraine!");
        logger.Dispose();

        _client.Content.ShouldMatchApproved(
            c =>
        {
            c.SubFolder(ApprovalsFolderName);
            c.WithScrubber(
                s => Regex.Replace(
                    s,
                    TimeStampRegEx,
                    TimeStampReplacement));
        });
    }
Example #12
0
        public static void Main()
        {
            var logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss} ({ThreadId}) [{Level}] {Message}{NewLine}{Exception}")
                         .WriteTo.NewRelic("NewRelicSinkDev", "SerilogDev")
                         .Enrich.WithMachineName()
                         .Enrich.WithThreadId()
                         .CreateLogger();

            logger.ForContext(PropertyNameConstants.TransactionName, "test::trans")
            .Information("Message in a transaction");

            const string template = "This is a simple {Level} message {Val}";

            logger.Verbose(template, LogEventLevel.Verbose, (int)LogEventLevel.Verbose);
            logger.Debug(template, LogEventLevel.Debug, (int)LogEventLevel.Debug);
            logger.Information(template, LogEventLevel.Information, (int)LogEventLevel.Information);
            logger.Warning(template, LogEventLevel.Warning, (int)LogEventLevel.Warning);

            // 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");
                logger.Error("A templated test message notifying of an error. Value {val}", 1);
            }

            logger.Dispose();
            Console.WriteLine("Press a key to exit.");
            Console.ReadKey(true);
        }
Example #13
0
        public async Task ExtraPropertiesShouldBeSentToLogzIo()
        {
            //Arrange
            var httpData = new List <HttpContent>();
            var log      = new LoggerConfiguration()
                           .Enrich.WithProperty("PropStr1", "banana")
                           .Enrich.WithProperty("PropInt1", 42)
                           .Enrich.WithProperty("PropInt2", -42)
                           .Enrich.WithProperty("PropFloat1", 88.8)
                           .Enrich.WithProperty("PropFloat2", -43.5)
                           .Enrich.WithProperty("PropBool1", false)
                           .Enrich.WithProperty("PropBool2", true)
                           .Enrich.WithProperty("PropEnum1", DateTimeKind.Utc)
                           .Enrich.WithProperty("PropEnum2", StringComparison.CurrentCultureIgnoreCase)
                           .Enrich.WithProperty("PropArr1", new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 })
                           .Enrich.WithProperty("PropArr2", new[] { "banana", "apple", "lemon" })
                           .Enrich.WithProperty("PropArr3", new object[] { 1, "banana", 3.5, false })
                           .Enrich.WithProperty("PropNull1", null)
                           .Enrich.WithProperty("PropDic1",
                                                new Dictionary <string, int> {
                { "banana", 2 }, { "apple", 5 }, { "lemon", 76 }
            })
                           .Enrich.WithProperty("PropObj1",
                                                new { Name = "banana", Itens = new[] { 1, 2, 3, 4 }, Id = 99, active = true })
                           .Enrich.WithProperty("PropObj2",
                                                new { Name = "banana", Itens = new[] { 1, 2, 3, 4 }, Id = 99, active = true }, true)
                           .WriteTo.Sink(new LogzioSink(new GoodFakeHttpClient(httpData), "testAuthCode", "testTyoe", 100,
                                                        TimeSpan.FromSeconds(1)))
                           .CreateLogger();

            //Act
            var logMsg = "This a Information Log Trace";

            log.Warning(logMsg);
            log.Dispose();

            //Assert
            httpData.Should().NotBeNullOrEmpty();
            httpData.Should().HaveCount(1);

            var data = await httpData.Single().ReadAsStringAsync();

            data.Should().NotBeNullOrWhiteSpace();

            var dataDic = JsonConvert.DeserializeObject <Dictionary <string, object> >(data);

            dataDic.Should()
            .ContainKey(
                "@timestamp");                      //LogzIo Requered a @timestamp (Iso DateTime) to indicate the time of the event.
            dataDic.Should().ContainKey("message"); //LogzIo Requered a lowercase message string
            dataDic["@timestamp"].Should().NotBeNull();
            dataDic["message"].Should().Be(logMsg);
            dataDic["level"].Should().Be(LogEventLevel.Warning.ToString());

            dataDic.Should().ContainKeys("properties.PropStr1", "properties.PropInt1", "properties.PropInt2",
                                         "properties.PropBool1", "properties.PropArr1", "properties.PropArr2",
                                         "properties.PropObj1", "properties.PropObj2", "properties.PropNull1",
                                         "properties.PropDic1", "properties.PropFloat1", "properties.PropFloat2",
                                         "properties.PropArr3", "properties.PropEnum1", "properties.PropEnum2");

            dataDic["properties.PropStr1"].Should().Be("banana");
            dataDic["properties.PropInt1"].Should().Be(42);
            dataDic["properties.PropInt2"].Should().Be(-42);
            dataDic["properties.PropFloat1"].Should().Be(88.8);
            dataDic["properties.PropFloat2"].Should().Be(-43.5);
            dataDic["properties.PropBool1"].Should().Be(false);
            dataDic["properties.PropBool2"].Should().Be(true);
            dataDic["properties.PropNull1"].Should().BeNull();
            dataDic["properties.PropEnum1"].Should().Be(DateTimeKind.Utc.ToString());
            dataDic["properties.PropEnum2"].Should().Be(StringComparison.CurrentCultureIgnoreCase.ToString());

            var dataDinamic = JObject.Parse(data);

            dataDinamic["properties.PropStr1"].Should().BeNullOrEmpty();
            dataDinamic["properties.PropArr1"].Should().BeOfType <JArray>();
            dataDinamic["properties.PropArr2"].Should().BeOfType <JArray>();
            dataDinamic["properties.PropArr3"].Should().BeOfType <JArray>();
            dataDinamic["properties.PropDic1"].Should().BeOfType <JObject>();
            dataDinamic["properties.PropObj2"].Should().BeOfType <JObject>();

            //TODO More Test for other Props
        }
Example #14
0
        private static async Task <int> Main()
        {
#if DEBUG
            // Uncomment for debuging.

            /*for (; ; )
             * {
             *  Console.WriteLine("waiting for debugger attach");
             *  if (Debugger.IsAttached) break;
             *  await System.Threading.Tasks.Task.Delay(3000);
             * }*/
#endif

            var cts = new CancellationTokenSource();
            AppDomain.CurrentDomain.ProcessExit += (s, e) =>
            {
                cts.Cancel();
            };

            IConfiguration configuration = GetConfigurationObject();

            Logger logger = new LoggerConfiguration()
                            .ReadFrom.Configuration(configuration.GetSection("Serilog"))
                            .MinimumLevel.Debug()
                            .WriteTo.File(
                AppDomain.CurrentDomain.BaseDirectory + @"/Gateway-Log-.txt",
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] ({SourceContext}) {Message:lj}{NewLine}{Exception}",
                restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug,
                rollingInterval: RollingInterval.Month)
#if DEBUG
                            .WriteTo.Console(
                restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information,
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u3}] ({SourceContext}) {Message:lj}{NewLine}{Exception}")
#endif
                            .CreateLogger();

            IServiceProvider servicesProvider = RegisterServices(logger);

            try
            {
                using (servicesProvider as IDisposable)
                {
                    var serviceLauncher = servicesProvider.GetRequiredService <ServiceLauncher>();
                    try
                    {
                        await serviceLauncher.ConfigureServicesAsync(cts.Token);

                        await serviceLauncher.StartServicesAsync(cts.Token);
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }
            #region Finalizing
            finally
            {
                logger.Information("Gateway is exiting...");
                logger.Dispose();
                cts.Dispose();
            }
            return(0);

            #endregion
        }