1:安装Log4Net的 NuGet 包:
我们通常之需要安装这一个包即可,其他的主包会自动被添加进来:
insatll-package Microsoft.Extensions.Logging.Log4Net.AspNetCore 3.0.0 (如果不行就直接NuGet可视化安装)!
2:Log4Net的配置文件的内容:
<?xml version="1.0" encoding="utf-8" ?> <log4net> <!-- Define some output appenders --> <appender name="rollingAppender" type="log4net.Appender.RollingFileAppender"> <file value="Errorlog\log.txt" /> <!--追加日志内容--> <appendToFile value="true" /> <!--防止多线程时不能写Log,官方说线程非安全--> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <!--可以为:Once|Size|Date|Composite--> <!--Composite为Size和Date的组合--> <rollingStyle value="Composite" /> <!--当备份文件时,为文件名加的后缀,这里可以作为每一天的日志分别存储不同的文件--> <datePattern value="yyyyMMdd".txt"" /> <StaticLogFileName value="false"/> <!--日志最大个数,都是最新的--> <!--rollingStyle节点为Size时,只能有value个日志--> <!--rollingStyle节点为Composite时,每天有value个日志--> <maxSizeRollBackups value="20" /> <!--可用的单位:KB|MB|GB--> <maximumFileSize value="3MB" /> <!--置为true,当前最新日志文件名永远为file节中的名字--> <staticLogFileName value="true" /> <!--输出级别在INFO和ERROR之间的日志--> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="DEBUG" /> <param name="LevelMax" value="FATAL" /> </filter> <layout type="log4net.Layout.PatternLayout"> <!--日志输出格式:时间 日志类型 日志内容--> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/> </layout> </appender> <!-- levels: OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL --> <root> <priority value="ALL"/> <level value="ALL"/> <appender-ref ref="rollingAppender" /> </root> </log4net>
3:在StartUp类中新增读取Log4Net的配置文件的代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using WebApp.Filters; namespace WebApp { using log4net; using log4net.Config; using log4net.Repository; public class Startup { public static ILoggerRepository repository { get; set; } public Startup(IConfiguration configuration) { Configuration = configuration; repository = LogManager.CreateRepository("rollingAppender"); XmlConfigurator.Configure(repository, new System.IO.FileInfo(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config"))); } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews();//configure => //-------全局异常过滤器 services.AddMvc(c => c.Filters.Add<CustomerExceptionFilterAttribute>()); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Student}/{action=Index}/{id?}"); }); } } }
4:Log4Net的文件修改为始终复制:
5:我们在Controller来简单的测试一下,代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using WebApp.Filters; namespace WebApp.Controllers { using log4net; using Microsoft.Extensions.Configuration; public class StudentController : Controller { private ILog log = LogManager.GetLogger(Startup.repository.Name,typeof(StudentController)); private IConfiguration config; public StudentController(IConfiguration config) { this.config = config; } [TypeFilter(typeof(CustomerActionFilterAttribute))] [TypeFilter(typeof(CustomerExceptionFilterAttribute))] [TypeFilter(typeof(CustomerResourceFilterAttribute))] public IActionResult Index() { string uid = config["mysqlserver:database"]; string infoName = config["mysqlserver:infos:1:age"]; log.Info("dsadsadsdsdsaderror"); log.Error("errorddddddddd"); int j = 0; // int i = 0 / j; ViewBag.uid = uid; ViewBag.infoname = infoName; ViewBag.Time = $"后台时间是:{ DateTime.Now.ToString()}"; return View(); } } }
6:查看效果如下截图:
7:后续难道每一个Controller都要这样写一下?感觉有些代码冗余了,下面做个小封装(当然我们还可以根据业务逻辑使用过滤器来处理):
==》 Core 3.0 读取系统配置文件(json文件里面的参数) 比较简单,直接截图了:
core3.1WebApi 下方便使用Log4Net ,另外Nlog都是差不多的使用: