網站首頁 編程語言 正文
這個日志框架使用的是ASP.NET Core的NLog,用來記錄每次請求信息和返回信息。
1.首先創建一個Web應用項目,我選擇的是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配置文件,內容如下:
<?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>
注意:運行項目時需要復制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());
}
}
再創建一個LogMiddlewareExtensions類:
/// <summary>
/// 這是擴展中間件
/// </summary>
public static class LogMiddlewareExtensions
{
public static IApplicationBuilder UseLog(this IApplicationBuilder builder)
{
return builder.UseMiddleware<LogMiddleware>();
}
}
這樣就編寫好一個自定義的中間件。
6.在Configure方法中調用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文件下生成日志文件。
原文鏈接:https://www.cnblogs.com/afei-24/p/10744297.html
相關推薦
- 2022-05-13 可變參C API va_list,va_start,va_arg_va_end以及c++可變參模板
- 2022-05-05 輕量級ORM框架Dapper應用之返回多個結果集_實用技巧
- 2022-10-08 Python使用plt.boxplot()函數繪制箱圖、常用方法以及含義詳解_python
- 2022-09-20 linux系統下用.sh文件執行python命令的方法_linux shell
- 2022-06-16 React中前端路由的示例代碼_React
- 2022-05-09 Python實現連接FTP并下載文件夾_python
- 2022-11-09 django中的auth模塊與admin后臺管理方法_python
- 2022-11-10 Android開發之AlertDialog實現彈出對話框_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支