log4net.config
<log4net><appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"><!--定义文件存放位置--><file value="log/" /><appendToFile value="true" /><rollingStyle value="Date" /><datePattern value="yyyyMMdd'.txt'" /><staticLogFileName value="false" /><param name="MaxSizeRollBackups" value="100" /><layout type="log4net.Layout.PatternLayout"><conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /></layout></appender><appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"><layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" /></appender><appender name="ElasticSearchAppender" type="log4net.ElasticSearch.ElasticSearchAppender, log4net.ElasticSearch"><layout type="log4net.Layout.PatternLayout,log4net"><param name="ConversionPattern" value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n" /></layout><connectionString value="Server=localhost;Index=log_test;Port=9200;rolling=false"/><lossy value="false" /><evaluator type="log4net.Core.LevelEvaluator"><threshold value="ALL" /></evaluator><bufferSize value="1" /></appender><root><level value="INFO" /> <appender-ref ref="ElasticSearchAppender" /><appender-ref ref="ConsoleAppender" /><!--文件形式记录日志--><appender-ref ref="RollingLogFileAppender" /></root> </log4net>
using Microsoft.AspNetCore.Mvc;namespace log4net直切ElasticSearch.Controllers;[ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase {private static readonly string[] Summaries = new[]{"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"};private readonly ILogger<WeatherForecastController> _logger;public WeatherForecastController(ILogger<WeatherForecastController> logger){_logger = logger;}[HttpGet(Name = "GetWeatherForecast")]public IEnumerable<WeatherForecast> Get(){ _logger.LogInformation("log4net写Elastic日志");return Enumerable.Range(1, 5).Select(index => new WeatherForecast{Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),TemperatureC = Random.Shared.Next(-20, 55),Summary = Summaries[Random.Shared.Next(Summaries.Length)]}).ToArray();} }