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都是差不多的使用: