serilog Getting Started

Getting Started

复制代码
using System;
using Serilog;

namespace SerilogExample
{
    class Program
    {
        static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Console()
                .WriteTo.File("logs\\myapp.txt", rollingInterval: RollingInterval.Day)
                .CreateLogger();

            Log.Information("Hello, world!");

            int a = 10, b = 0;
            try
            {
                Log.Debug("Dividing {A} by {B}", a, b);
                Console.WriteLine(a / b);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Something went wrong");
            }

            Log.CloseAndFlush();
            Console.ReadKey();
        }
    }
}
复制代码

 

Serilog.Settings.AppSettings 

An XML <appSettings> reader for Serilog

To read configuration from <appSettings> use the ReadFrom.AppSettings() extension method on your LoggerConfiguration:

Log.Logger = new LoggerConfiguration()
  .ReadFrom.AppSettings()
  ... // Other configuration here, then
  .CreateLogger()

You can mix and match XML and code-based configuration, but each sink must be configured either using XML or in code - sinks added in code can't be modified via app settings.

Configuration syntax

To configure the logger, an <appSettings> element should be included in the program's App.config or Web.config file.

https://github.com/serilog/serilog/wiki/AppSettings 

Serilog supports a simple <appSettings>-based configuration syntax in App.config and Web.config files to set the minimum level, enrich events with additional properties, and control log output.

Serilog is primarily configured using code, with settings support intended as a supplementary feature. It is not comprehensive but most logger configuration tasks can be achieved using it.

 

https://github.com/serilog/serilog-sinks-elasticsearch#quick-start

elasticsearch的配置在单独的项目里面提到

复制代码
 <appSettings>
    <add key="serilog:using" value="Serilog.Sinks.Elasticsearch"/>
    <add key="serilog:write-to:Elasticsearch.nodeUris" value="http://localhost:9200;http://remotehost:9200"/>
    <add key="serilog:write-to:Elasticsearch.indexFormat" value="custom-index-{0:yyyy.MM}"/>
    <add key="serilog:write-to:Elasticsearch.templateName" value="myCustomTemplate"/>
    <add key="serilog:write-to:Elasticsearch.typeName" value="myCustomLogEventType"/>
    <add key="serilog:write-to:Elasticsearch.pipelineName" value="myCustomPipelineName"/>
    <add key="serilog:write-to:Elasticsearch.batchPostingLimit" value="50"/>
    <add key="serilog:write-to:Elasticsearch.period" value="2"/>
    <add key="serilog:write-to:Elasticsearch.inlineFields" value="true"/>
    <add key="serilog:write-to:Elasticsearch.restrictedToMinimumLevel" value="Warning"/>
    <add key="serilog:write-to:Elasticsearch.bufferBaseFilename" value="C:\Temp\SerilogElasticBuffer"/>
    <add key="serilog:write-to:Elasticsearch.bufferFileSizeLimitBytes" value="5242880"/>
    <add key="serilog:write-to:Elasticsearch.bufferLogShippingInterval" value="5000"/>
    <add key="serilog:write-to:Elasticsearch.bufferRetainedInvalidPayloadsLimitBytes" value="5000"/>
    <add key="serilog:write-to:Elasticsearch.bufferFileCountLimit " value="31"/>
    <add key="serilog:write-to:Elasticsearch.connectionGlobalHeaders" value="Authorization=Bearer SOME-TOKEN;OtherHeader=OTHER-HEADER-VALUE" />
    <add key="serilog:write-to:Elasticsearch.connectionTimeout" value="5" />
    <add key="serilog:write-to:Elasticsearch.emitEventFailure" value="WriteToSelfLog" />
    <add key="serilog:write-to:Elasticsearch.queueSizeLimit" value="100000" />
    <add key="serilog:write-to:Elasticsearch.autoRegisterTemplate" value="true" />
    <add key="serilog:write-to:Elasticsearch.autoRegisterTemplateVersion" value="ESv2" />
    <add key="serilog:write-to:Elasticsearch.overwriteTemplate" value="false" />
    <add key="serilog:write-to:Elasticsearch.registerTemplateFailure" value="IndexAnyway" />
    <add key="serilog:write-to:Elasticsearch.deadLetterIndexName" value="deadletter-{0:yyyy.MM}" />
    <add key="serilog:write-to:Elasticsearch.numberOfShards" value="20" />
    <add key="serilog:write-to:Elasticsearch.numberOfReplicas" value="10" />
    <add key="serilog:write-to:Elasticsearch.formatProvider" value="My.Namespace.MyFormatProvider, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.connection" value="My.Namespace.MyConnection, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.serializer" value="My.Namespace.MySerializer, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.connectionPool" value="My.Namespace.MyConnectionPool, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.customFormatter" value="My.Namespace.MyCustomFormatter, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.customDurableFormatter" value="My.Namespace.MyCustomDurableFormatter, My.Assembly.Name" />
    <add key="serilog:write-to:Elasticsearch.failureSink" value="My.Namespace.MyFailureSink, My.Assembly.Name" />
  </appSettings>
复制代码

 

 

 

Watch the config file at runtime

Try to figure out the feature about watch the App.config at runtime like log4net and NLog
https://stackoverflow.com/questions/25477415/how-can-i-reconfigure-serilog-without-restarting-the-application
https://stackoverflow.com/questions/50715913/serilog-equivalent-to-log4net-config-watch
The above two links have no useful info about reload all settings in App.config.

Here is another link https://stackoverflow.com/questions/53449596/reload-serilog-json-configuration-on-changes-in-net-core-2-1/60474967#60474967
The current Serilog implementation (2.9.0) is such that it is unable to fully reload settings. To work around this issue without introducing additional dependencies, avoid creating static loggers and follow the example provided here: https://github.com/akovac35/Logging/blob/v1.0.4/src/com.github.akovac35.Logging.Serilog/SerilogHelper.cs

Will you consider to implement this feature?

 

Change logger/sink configuration at runtime?

Thanks for the weigh-in @damianh. I agree there are some rough edges around this scenario, especially existing contextual loggers, as you point out. I think the way existing loggers continue to point to the sinks they were created with falls out from the immutable/stateless design, which isn't ideal here but brings a lot of other benefits. Do you think your workaround is something that could be made general? It seems like the best approach available at this point.... :-)

I think the new WriteTo.Logger() method added in the latest Serilog gets rid of your casting issue:

Log.Logger = new LoggerConfiguration()
      .WriteTo.Logger(Log.Logger)
      .WriteTo.Console().CreateLogger();

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(357)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-07-09 __doPostBack function
2019-07-09 ASP.NET postback with JavaScript (UseSubmitBehavior)
2019-07-09 ClientScriptManager 和 ScriptManager RegisterClientScriptBlock
2019-07-09 sonarqube修改自己的图像avatar
2015-07-09 C#中的异常处理
2015-07-09 How to: Create a Windows Communication Foundation Client
2015-07-09 Sum of Digits / Digital Root
点击右上角即可分享
微信分享提示