user123456
user123456

Reputation: 2659

How Do I create a logger using .net core serilog?

I am doing serilog, I want to create a logger class ?

I have this method ?

var configuration = new ConfigurationBuilder()
           .AddJsonFile("appsettings.json")
           .Build();
            var logger = new LoggerConfiguration().MinimumLevel.Debug()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();

Can sombedy explain to me how this class is being generated ?

{
  "Serilog": {
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "C:\\Users\\m_243\\OneDrive\\Desktop\\Adaa\\HRSoultion\\API\\APISerilogs\\AppLogs.log.txt",
          "rollingInterval": "Month"
        }
      }
    ]
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "HrSoultion": "server=.;database=HrSoultionv2;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Upvotes: 0

Views: 988

Answers (1)

Qing Guo
Qing Guo

Reputation: 9082

Serilog.Sinks.File - Used for writing logs in to one or more files.

Below I use a demo (applicatioan is webapi Core3.1) to explain implementing Serilog to log in a file.

First, install the necessary packages given below.

 <PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
    <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />

Second, modify the appsettings.json file to include the path for the log file.

"Serilog": {
    "Minimulevel": {
      "Default": "Information",
      "Overrides": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Warning"
      }
    },
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "WriteTo": [        
      {
        "Name": "File",
        "Args": {
          "path": "./bin/log.txt",
          "rollingInterval": "Day"
        }
      }
    ] 
  }

Then modify the Program.cs file ,call ReadFrom.Configuration() to read these values from the JSON file to configure the logger:

 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>();
                })
            .UseSerilog((hostingContext,LoggerConfiguration)=>
                {
                    LoggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration);

                });
    }

result:

enter image description here

Upvotes: 1

Related Questions