.net core Web Api中使用log4net日志

1.建立一个.net core Web Api程序,使用nuget下载log4net

.net core Web Api中使用log4net日志_第1张图片

2.建立log4net.config文件



	
	
		
		
			
		
	
	
	
		
		
		
		
		
		
		
		
		
		
		
			
		
	
	
		
		
		
	

3.在Program.cs中进行配置

.net core Web Api中使用log4net日志_第2张图片

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        //进行配置,支持ico
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging=>
            {
                logging.AddLog4Net();
            })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup();
                });
    }
}

4.使用

.net core Web Api中使用log4net日志_第3张图片

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class TestController : ControllerBase
    {
        public TestController(ILogger logger )
        {
            Logger = logger;
        }

        public ILogger Logger = null;

        [HttpGet]
        public string Get()
        {
            Logger.LogInformation("1", "3213","123");
            Logger.LogError("2", "3213", "1234");
            Logger.LogDebug("3", "3213", "1235");
            Logger.LogTrace("4", "3213", "1236");
            return ".net core-001";
        }
    }
}

来源:.net core Web Api中使用log4net日志_.netcore配置 log4net-CSDN博客

你可能感兴趣的:(.NET,CORE,.netcore)