Start by installing two packages

NLog
NLog.Web.AspNetCore
Copy the code
public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .UseNLog();
    }
Copy the code
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            logger.LogError("Hello");

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/".async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }
Copy the code
public class HomeConroller
    {
        public ILogger<HomeConroller> _Logger;

        public HomeConroller(ILogger<HomeConroller> logger){ _Logger = logger; }}Copy the code

Configuration file nlog.config

<? 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"
      internalLogLevel="Info"
      internalLogFile="c:\temp\internal-nlog.txt"> <! -- enable asp.net core layout renderers --> <extensions> <add assembly="NLog.Web.AspNetCore"/> </extensions> <! -- the targets to write to --> <targets> <! -- write logs to file --> <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"/ > <! -- another file log, only own logs. Uses some ASP.NET core renderers --> <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}"/> </targets> <! -- rules to mapfromlogger name to target --> <rules> <! --All logs, includingfrom Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile"/ > <! --Skip non-critical Microsoft logsand so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Info" final="true"/ > <! -- BlackHole without writeTo --> <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>
Copy the code