. NET core 2.0 write log files using Nlog

Source: Internet
Author: User
Tags dotnet

Original Address: Portal

I've seen the Linezero, but I've never written a log file successfully. According to Chiling's success, the following text:

Recently studied the use of nlog, simply into the door.

The implementation of the function, for different logs, different records, there are system run log, and the individual in the program to write the Exception log. is placed on IIS after it has been published. To view the log information

Two blog entries were referenced.

1.http://www.voidcn.com/blog/aojiancc2/article/p-6672009.html2.http://www.cnblogs.com/linezero/p/logging.html

Personally feel that the first article is written in detail. The second one may be written by the great God, some of the details are not specially noticed.

The two blogs have been written in great detail, and I repeat them, as well as reminding them of the things that need to be noticed, and some of the doubts that individuals have in them.

First we build a core 2.0 project, because the current 2.0 is not officially released, if you want to use 2.0 need to install the preview version of VS

We need to introduce these packages and we'll use them. This is part of my *.csproj file. (note here, if it is Core2.0 project directly with more than 2.0 packages, otherwise run in the VS is no problem, running in the Windows environment is not a problem, but in Linux will be problematic, in the restore, will give you an error, Let you upgrade the package to more than 2.0. The problem itself did not notice that originally thought of these version control and other things, must be backwards-compatible. But that was the problem two days ago when the test was released on Linux with Docker. )

<ItemGroup>    <packagereference include= "Microsoft.AspNetCore.All" version= "2.0.0-preview1-final"/ >    <packagereference include= "NLog" version= "5.0.0-beta09"/> <packagereference include=    " NLog.Web.AspNetCore "version=" 4.4.1 "/>    <packagereference include=" System.Text.Encoding.CodePages " version= "4.3.0"/>  </ItemGroup>

Open our StartUp.cs file

Add the code below

        public void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory)        {            Encoding.registerprovider (codepagesencodingprovider.instance);//This is to prevent Chinese garbled            loggerfactory.addnlog (); Add Nlog            env. Configurenlog ("Nlog.config");//Read Nlog configuration file           //other Code        }

No dependency injection configuration is required in the Configservie method

Because here we have added the information to read the Nlog configuration file

So we're going to add "Nlog.config file."

Create a new XML file name for your env. Configurenlog ("Nlog.config"); the name of the string parameter worn inside.

 1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <nlog xmlns= "http://www.nlog-project.org/schemas/NLog.xsd" 3 x Mlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 4 autoreload= "true" 5 internalloglevel= "Warn" 6 int ernallogfile= "Internal-nlog.txt" > 7 8 <!--define various log targets--> 9 <targets>10 <!--WR                  ITE logs to file-->12 <target xsi:type= "file" Name= "Allfile" Filename= "Nlog-all-${shortdate}.log" 13 Layout= "${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}"/>14 <target xsi:type= "File "Name=" Ownfile-web "filename=" Nlog-my-${shortdate}.log "layout=" ${longdate}|${logger}|${uppercase:${le Vel}}|${message} ${exception} "/>17 <target xsi:type=" Null "name=" blackhole "/>19 </targets>21 <rules>23 <!--all logs, including from microsoft-->24 <logger name= "*" minlevel= "Trace" Writet  o= "Allfile"/>25 26   <!--Skip Microsoft logs and so logs only own logs-->27 <logger name= "microsoft.*" minlevel= "Trace" writeto=  "Blackhole" final= "true"/>28 <logger name= "*" minlevel= "Trace" writeto= "Ownfile-web"/>29 </rules>30 </nlog>

Make the following changes in Homecontroler (I've combined the usage of their two people)

public class Homecontroller:controller    {        private readonly ilogger

One might wonder: how the logger in the constructor is put in, without the dependency injection. What I personally know is not particularly in-depth, and visual inspection is through App.addnlog (). to inject.

We then modified our Appsetting.json file to adjust the log level to information. The default is debug

{"  Logging": {    "includescopes": false,    "Debug": {      "LogLevel": {        "Default": "Information"      }    },    "Console": {      "LogLevel": {        "Default": "Information"      }  }}}

At this time we directly run F5 under the/bin/debug/netcoreapp2.0 folder is not see the log file, in our project root directory open DOS window. dotnet Restore, then dotnet run a bit to access the address, and then enter that folder to see the log file.

To illustrate these two files, the first one is all the log records when the Web site is running, and the second one is just the Exception log records that we write ourselves.

Since I'm going to put it on IIS, I'm going to publish it in VS, just publish it, and publish it with dotnet publish, and I'll use the first one, after the release is done. This time if we run directly, there is no way to run the cause is the time of release. Without putting our nlog.config files in the published directory, we need to manually copy this file to our published directory. (Another workaround: Right-click File--Properties--Copy to output directory)

Then set the permissions for this folder to be published, add the Everyone role, and give it permission to read and write.

The published directory is then bound to IIS, and in the application pool, the Web site that you just tied to IIS is changed to unmanaged mode. Then restart the Web site and run the domain name you bound in the browser. You can access this URL directly.

If an error occurs. Please go to the publisher's folder and execute the dotnet run. If the project runs successfully, check to see if everyone has permission to read and write, and restart the IIS server. If not, please re-publish. can solve this problem.

This is the log file directory after I run the build is Publishoutput

. NET core 2.0 write log files using Nlog

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.