1、NuGet添加2个包:
Microsoft.Extensions.Logging.Log4Net.AspNetCore
log4net.Kafka.Core
2、Program里修改CreateWebHostBuilder:
public class Program { public static void Main(string[] args) { System.Threading.ThreadPool.SetMinThreads(200, 200); // NLogBuilder.ConfigureNLog("Config/nlog.config"); // NLogBuilder.ConfigureNLog("Config/nlog.config").GetCurrentClassLogger(); CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args). ConfigureLogging((context, loggingbuilder) => { //该方法需要引入Microsoft.Extensions.Logging名称空间 loggingbuilder.AddFilter("System", LogLevel.Warning); //过滤掉系统默认的一些日志 loggingbuilder.AddFilter("Microsoft", LogLevel.Warning);//过滤掉系统默认的一些日志
//最好带上这句话
loggingbuilder.SetMinimumLevel(LogLevel.Debug); //var path = Directory.GetCurrentDirectory() + "\\log4net.config"; //不带参数:表示log4net.config的配置文件就在应用程序根目录下,也可以指定配置文件的路径 loggingbuilder.AddLog4Net("Config/log4net.config"); }) .UseStartup<Startup>(); }
添加配置文件:在Config目录下创建log4net.config,内容如下:
<?xml version="1.0" encoding="utf-8" ?> <log4net> <appender name="KafkaAppender" type="log4net.Kafka.Core.KafkaAppender, log4net.Kafka.Core"> <KafkaSettings> <broker value="地址1:端口,地址2:端口,地址3:端口" /> <topic value="kafka的topic" /> </KafkaSettings> <layout type="log4net.Kafka.Core.KafkaLogLayout,log4net.Kafka.Core" > <appid value="sysName" /> </layout> </appender> <root> <level value="ALL"/> <appender-ref ref="KafkaAppender" /> </root> </log4net>
broker: Kafka 服务地址,集群可使用,分割;
topic:日志对应的 Topic 名称;
appid:服务唯一标识,辅助识别日志来源;
接下来就可以直接使用了:
using Microsoft.Extensions.Logging;
[Route("api/[controller]")] public class ValuesController : Controller { private readonly ILogger _logger; public ValuesController(ILogger<ValuesController> logger) { _logger = logger; } // GET api/values [HttpGet] public IEnumerable<string> Get() { _logger.LogInformation("根据appId最后一次测试Kafka!"); return new string[] { "value1", "value2" }; } }
上线后发现会有记录不下来的情况。解决方法:
appsettings.json文件里有创建项目时候,自动了默认日志级别(Warning)。需要改掉:
"Logging": { "LogLevel": { "Default": "Information", "System": "Warning", "Microsoft": "Warning" }
使用注入的方式,有时候用起来不是很方便,我还是比较喜欢封装个Helper类:
using log4net; using log4net.Config; using log4net.Repository; using System; using System.Diagnostics; using System.IO; using System.Text; namespace Common { /// <summary> /// Helper类 /// </summary> public class LogHelper { private static ILoggerRepository repository { get; set; } private static ILog _log; private static ILog log { get { if (_log == null) { Configure(); } return _log; } } public static void Configure(string repositoryName = "NETCoreRepository", string configFile = "Config/log4net.config") { repository = LogManager.CreateRepository(repositoryName); XmlConfigurator.Configure(repository, new FileInfo(configFile)); _log = LogManager.GetLogger(repositoryName, ""); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="e"></param> public static void Debug(string message, Exception e = null) { log.Debug(GetCurrentMethodFullName() + " " + message, e); } public static void Info(string message, Exception e = null) { log.Info(GetCurrentMethodFullName() + " " + message, e); } public static void Warn(string message, Exception e = null) { log.Warn(GetCurrentMethodFullName() + " " + message, e); } public static void Error(string message, Exception e = null) { log.Error(GetCurrentMethodFullName() + " " + message, e); } public static void Fatal(string message, Exception e = null) { log.Fatal(GetCurrentMethodFullName() + " " + message, e); } private static string GetCurrentMethodFullName() { try { StringBuilder sb = new StringBuilder(); StackTrace stackTrace = new StackTrace(); return string.Concat(stackTrace.GetFrame(2).GetMethod().DeclaringType.ToString(), ".", stackTrace.GetFrame(2).GetMethod().Name); } catch { return ""; } } } }
这样,就可以在任意地方使用了: