ASP.NET?Core使用自定義日志中間件
這個日志框架使用的是ASP.NET Core的NLog,用來記錄每次請求信息和返回信息。
1.首先創(chuàng)建一個Web應(yīng)用項目,我選擇的是MVC模板:
2.使用NuGet添加Microsoft.Extensions.Logging和NLog.Extensions.Logging
3.修改Configure方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddNLog(); //添加NLog NLog.LogManager.LoadConfiguration("nlog.config"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
4.添加nlog.config配置文件,內(nèi)容如下:
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="Warn" internalLogFile="internal-nlog.txt"> <!--define various log targets--> <targets> <!--write logs to file--> <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="ownFile-web" fileName="nlog-my-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="Null" name="blackhole" /> </targets> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip Microsoft logs and so log only own logs--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>
注意:運行項目時需要復(fù)制nlog.config到debug
5.接下來開始自定義中間件
添加一個LogMiddleware類:
public class LogMiddleware { private readonly RequestDelegate _next; private readonly ILogger<LogMiddleware> _logger; public LogMiddleware(RequestDelegate next, ILogger<LogMiddleware> logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext context) { _logger.LogInformation("Request Url:" + context.Request.Path +Environment.NewLine + "Body:" + context.Request.Body.ToString()); await _next.Invoke(context); _logger.LogInformation("Response Url:" + context.Request.Path + Environment.NewLine + "Body:" + context.Response.Body.ToString()); } }
再創(chuàng)建一個LogMiddlewareExtensions類:
/// <summary> /// 這是擴展中間件 /// </summary> public static class LogMiddlewareExtensions { public static IApplicationBuilder UseLog(this IApplicationBuilder builder) { return builder.UseMiddleware<LogMiddleware>(); } }
這樣就編寫好一個自定義的中間件。
6.在Configure方法中調(diào)用app.UseLog()
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddNLog(); //添加NLog NLog.LogManager.LoadConfiguration("nlog.config"); app.UseLog(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
運行代碼,會在debug文件下生成日志文件。
到此這篇關(guān)于ASP.NET Core使用自定義日志中間件的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
.net core使用redis基于StackExchange.Redis
這篇文章主要為大家詳細介紹了.net core使用redis基于StackExchange.Redis的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04asp.net生成靜態(tài)后冗余代碼,去掉viewstate生成的代碼
asp.net生成的viewstate垃圾信息超過了20K,如果頁面前二K不是內(nèi)容會被引擎處罰,所以我們需要清理下asp.net生成靜態(tài)后冗余代碼2012-10-10ASP.NET WebAPI2復(fù)雜請求跨域設(shè)置的方法介紹
這篇文章主要給大家介紹了關(guān)于ASP.NET WebAPI2復(fù)雜請求跨域設(shè)置的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者使用ASP.NET具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07Win2008 server + IIS7 設(shè)置身份模擬(ASP.NET impersonation)
IIS7 與 IIS 6 相比有了很大的改動,原來在 IIS 6 下可以的設(shè)置到了 IIS 7 下有的會發(fā)生變化。身份模擬的配置上,IIS7 和 IIS6有很大不同,網(wǎng)上IIS6的身份模擬的文章比較多,但介紹IIS7的比較少,我把的一些折騰的經(jīng)驗在這篇博客中寫下來,以供參考2011-10-10