Net Core platform flexible and simple logging framework Nlog first Experience

Source: Internet
Author: User
Tags configuration settings

Net Core platform flexible and simple logging framework Nlog first Experience

"[Net Core integrated exceptionless distributed logging function and global exception filtering][https://www.cnblogs.com/yilezhu/p/9339017.html] shared over the last few days]" some people say that compared to weight, Deployment of the production environment is also more troublesome. So there's this article today. If your project (Web site or small-to-medium project) is not very large and the log volume is not much, you can consider the combination of nlog+mysql. Because the Nlog features high performance, ease of use, ease of expansion and flexible configuration, you can quickly integrate logging capabilities.
Yilezhu
This article link: https://www.cnblogs.com/yilezhu/p/9416439.html

What is Nlog?

Here is still a brief introduction, in order to let small white also know. Nlog is a flexible, free logging platform for a variety of applications. NET platform, including. NET Core. Nlog can be easily written to multiple log warehouses (database, file, console) by simply configuring it.

Nlog in net core how to use AH?
    1. You have to create a new ASP. NET core project before you use it. Let's take the net core API for example. As shown in the Net Core API project that the blogger has just created.

  1. What to do after building a project, of course, to add references. You can use NuGet or command to install it at your own whim.

    Install-Package NLog -Version 4.5.7Install-Package NLog.Web.AspNetCore -Version 4.5.4
  2. It says that Nlog can be used simply by modifying the configuration, and then creating a new Nlog configuration file. You can install it either through NuGet or the package console, or you can create a new Nlog.config file yourself. Install it from the package console.

    Install-Package NLog -Version 4.5.7

    After installation see the project directory more than one nlog.config file. It is important to note that the right-click setting of this Nlog.config property is "Always copy"

  3. Open the Nlog.config file, look inside the structure, find that there are two important nodes, one is

    <?xml version= "1.0" encoding= "Utf-8"? ><nlog xmlns= "Http://www.nlog-project.org/schemas/NLog.xsd" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" autoreload= "true" throwexceptions= "true" internalloglevel= "Off" > <targets> <target xsi:type= "Null" name= "blackhole"/> <target name= "database" xsi:type= "Da Tabase "dbprovider=" MySql.Data.MySqlClient.MySqlConnection, Mysql.data "connectionstring=" server =127.0.0.1;database=nlog;user id=root;password=123456; Sslmode=none "> <!--CREATE TABLE ' log ' (' Id ' int () unsigned not NULL auto_increment, ' Applicat  Ion ' varchar ' default NULL, ' logged ' datetime default NULL, ' level ' varchar (+) default NULL, ' Message ' varchar (512) Default NULL, ' Logger ' varchar (+) default NULL, ' Callsite ' varchar (+) default NULL, ' Exception ' varchar (+) Defau LT NULL, PRIMARY KEY (' Id ')) Engine=innodb auto_increment=2 DEFAULT charset=utf8;--> &Lt;commandtext> INSERT into Nlog.log (application, logged, level, Message, Logger, CallSite, EXCEP      tion) VALUES (@Application, @Logged, @Level, @Message, @Logger, @Callsite, @Exception); </commandText> <parameter name= "@application" layout= "Nlogtestdemo"/> <parameter name= "@logge D "layout=" ${date} "/> <parameter name=" @level "layout=" ${level} "/> <parameter name=" @message "Layo ut= "${message}"/> <parameter name= "@logger" layout= "${logger}"/> <parameter name= "@callSite" layou t= "${callsite:filename=true}"/> <parameter name= "@exception" layout= "${exception:tostring}"/> </targ Et> </targets> <rules> <!--Skip Microsoft logs and so logs only own logs--> <logger name= "M Icrosoft.* "minlevel=" Trace "writeto=" Blackhole "final=" true "/> <logger name=" nlogtestdemo.* "minlevel=" Info "W riteto= "Database"/> &Lt;/rules></nlog> 
  4. In the above code, I am using the Nlog configuration to write MySQL as an example. The following can be used in a simple way. First you need to be in. First in the startup of the Configure to join the middleware:

     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            if (env.IsDevelopment())            {                app.UseDeveloperExceptionPage();            }            //使用NLog作为日志记录工具            loggerFactory.AddNLog();            //引入Nlog配置文件            env.ConfigureNLog("Nlog.config");            //app.AddNLogWeb();            app.UseMvc();        }
  5. The following configuration is done in program:

    public class Program    {        public static void Main(string[] args)        {            CreateWebHostBuilder(args).Build().Run();        }        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>            WebHost.CreateDefaultBuilder(args)            .UseNLog()                .UseStartup<Startup>();    }
  6. Here you can play happily in the code,

      private readonly Logger nlog = LogManager.GetCurrentClassLogger(); //获得日志实;        // GET api/values        [HttpGet]        public ActionResult<string> Get()        {            nlog.Log(NLog.LogLevel.Debug, $"yilezhu测试Debug日志");            nlog.Log(NLog.LogLevel.Info, $"yilezhu测试Info日志");            try            {                throw new Exception($"yilezhu故意抛出的异常");            }            catch (Exception ex)            {                nlog.Log(NLog.LogLevel.Error, ex, $"yilezhu异常的额外信息");            }            return "yilezhu的返回信息";        }
  7. Run the project below, and in the database you can see the logged log information as follows:

    Here you might ask why there is no debug information output, because the lowest level of logging for the Nlog configuration settings above is info. So debug messages that are smaller than the info level are not logged. If you want to record it, set this level to debug or the trace that is smaller than debug can be recorded. As shown in the following:

Summarize

This article begins with the exceptionless deployment difficulties of the distributed logging framework, then leads to a lightweight and easy-to-use Nlog log framework, and a simple API project that describes how Nlog is used in net core. It also gives the configuration of the Nlog log records in MySQL. As well as MySQL's build table statements. I hope we can have some reference!

Net Core platform flexible and simple logging framework Nlog first Experience

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.