Skip to content

Commit

Permalink
Simplify the Log4net notation
Browse files Browse the repository at this point in the history
简化规范log4net的写法
  • Loading branch information
anjoy8 committed May 6, 2020
1 parent 63c5884 commit ecaffb6
Show file tree
Hide file tree
Showing 12 changed files with 55 additions and 223 deletions.
29 changes: 26 additions & 3 deletions .docs/contents/guide/cheat-sheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -396,9 +396,32 @@ models = _mapper.Map<BlogViewModels>(blogArticle);

## Log4

精力有限,还是更新中...
如果你愿意帮忙,可以直接在GitHub中,提交pull request,
我会在后边的贡献者页面里,列出你的名字和项目地址做推广
通过集成,完美配合 `NetCore` 官方的 `ILogger<T>` 接口:
Program.cs
```
webBuilder
.UseStartup<Startup>()
.ConfigureLogging((hostingContext, builder) =>
{
//该方法需要引入Microsoft.Extensions.Logging名称空间
builder.AddFilter("System", LogLevel.Error); //过滤掉系统默认的一些日志
builder.AddFilter("Microsoft", LogLevel.Error);//过滤掉系统默认的一些日志
//添加Log4Net
//var path = Directory.GetCurrentDirectory() + "\\log4net.config";
//不带参数:表示log4net.config的配置文件就在应用程序根目录下,也可以指定配置文件的路径
//需要添加nuget包:Microsoft.Extensions.Logging.Log4Net.AspNetCore
builder.AddLog4Net();
});
```

然后直接在需要的地方注入使用,比如在控制器中
` public UserController(ILogger<UserController> logger)`

然后就可以使用了。


## MemoryCache

精力有限,还是更新中...
Expand Down
30 changes: 1 addition & 29 deletions .docs/contents/guide/function-sheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,32 +48,4 @@
【SQL语句】:SELECT `bID`,`bsubmitter`,`btitle`,`bcategory`,`bcontent`,`btraffic`,`bcommentNum`,`bUpdateTime`,`bCreateTime`,`bRemark`,`IsDeleted` FROM `BlogArticle` WHERE ( `bID` = @bID0 )


6、控制器使用 ILogger< blogcontroller >

注意:这种方式并不太友好,除了会加载很多不必要的启动信息以为,目前只能生成到异常日志里,这里我建议使用Log4Net自己的方案:
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(typeof(GlobalExceptionsFilter));
或者我自己写的日志方法:
LogLock.OutSql2Log("RequestResponseLog", new string[] { "Request Data:", content });

开启方式:appsettings.json -> Middleware -> RecordAllLogs 节点为true。
文件路径:web目录下,Log/GlobalExcepLogs_{日期}.log。
功能描述:记录项目中的所有日志打印,除非在手动控制日志的输出,否则会打印很多日志。
举例来说:
--------------------------------

2020-02-17 11:15:07,049|
Request finished in 564.826ms 200 application/json;charset=utf-8
--------------------------------
2020-02-17 11:16:19,512|
Request starting HTTP/1.1 GET http://localhost:8081/api/Blog/DetailNuxtNoPer?id=1
--------------------------------
2020-02-17 11:16:19,882|
AuthenticationScheme: Bearer was not authenticated.
--------------------------------
2020-02-17 11:16:28,835|
xxxxxxxxxxxxxxxxxxx
--------------------------------


95 changes: 0 additions & 95 deletions Blog.Core.Common/LogHelper/L4n/Log4NetLogger.cs

This file was deleted.

39 changes: 0 additions & 39 deletions Blog.Core.Common/LogHelper/L4n/Log4NetProvider.cs

This file was deleted.

5 changes: 5 additions & 0 deletions Blog.Core/Blog.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
<None Remove="Hubs\**" />
</ItemGroup>

<ItemGroup>
<Compile Remove="Extensions\Log4netExtensions.cs" />
</ItemGroup>

<ItemGroup>
<None Remove="index.html" />
</ItemGroup>
Expand All @@ -39,6 +43,7 @@
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson" Version="5.0.0-preview.2.20167.3" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="5.0.0-preview.2.20160.3" />
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="3.1.0" />
<PackageReference Include="MiniProfiler.AspNetCore.Mvc" Version="4.1.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.3.3" />
Expand Down
5 changes: 3 additions & 2 deletions Blog.Core/Blog.Core.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions Blog.Core/Controllers/UserController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class UserController : ControllerBase
readonly IUserRoleServices _userRoleServices;
readonly IRoleServices _roleServices;
private readonly IUser _user;
private readonly ILogger<BlogController> _logger;
private readonly ILogger<UserController> _logger;

/// <summary>
/// 构造函数
Expand All @@ -39,7 +39,7 @@ public class UserController : ControllerBase
/// <param name="roleServices"></param>
/// <param name="user"></param>
/// <param name="logger"></param>
public UserController(IUnitOfWork unitOfWork, ISysUserInfoServices sysUserInfoServices, IUserRoleServices userRoleServices, IRoleServices roleServices, IUser user, ILogger<BlogController> logger)
public UserController(IUnitOfWork unitOfWork, ISysUserInfoServices sysUserInfoServices, IUserRoleServices userRoleServices, IRoleServices roleServices, IUser user, ILogger<UserController> logger)
{
_unitOfWork = unitOfWork;
_sysUserInfoServices = sysUserInfoServices;
Expand Down Expand Up @@ -98,8 +98,10 @@ public async Task<MessageModel<PageModel<sysUserInfo>>> Get(int page = 1, string

// GET: api/User/5
[HttpGet("{id}")]
[AllowAnonymous]
public string Get(string id)
{
_logger.LogError("test wrong");
return "value";
}

Expand Down
24 changes: 0 additions & 24 deletions Blog.Core/Extensions/Log4netExtensions.cs

This file was deleted.

5 changes: 1 addition & 4 deletions Blog.Core/Filter/GlobalExceptionFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,6 @@ public class GlobalExceptionsFilter : IExceptionFilter
private readonly IWebHostEnvironment _env;
private readonly IHubContext<ChatHub> _hubContext;
private readonly ILogger<GlobalExceptionsFilter> _loggerHelper;
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(typeof(GlobalExceptionsFilter));


public GlobalExceptionsFilter(IWebHostEnvironment env, ILogger<GlobalExceptionsFilter> loggerHelper, IHubContext<ChatHub> hubContext)
{
Expand Down Expand Up @@ -51,7 +48,7 @@ public void OnException(ExceptionContext context)


//采用log4net 进行错误日志记录
log.Error(json.Message + WriteLog(json.Message, context.Exception));
_loggerHelper.LogError(json.Message + WriteLog(json.Message, context.Exception));

_hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait();

Expand Down
2 changes: 1 addition & 1 deletion Blog.Core/Log4net.config
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
<staticLogFileName value="false" />

<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date| %newline%message%newline--------------------------------%newline" />
<conversionPattern value="%date| %-5level %newline%message%newline--------------------------------%newline" />
</layout>
</appender>

Expand Down
22 changes: 9 additions & 13 deletions Blog.Core/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,6 @@ public class Program
private static readonly ILog log = LogManager.GetLogger(typeof(Program));
public static void Main(string[] args)
{
XmlDocument log4netConfig = new XmlDocument();
log4netConfig.Load(File.OpenRead("Log4net.config"));

var repo = log4net.LogManager.CreateRepository(
Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));

log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);

// 生成承载 web 应用程序的 Microsoft.AspNetCore.Hosting.IWebHost。Build是WebHostBuilder最终的目的,将返回一个构造的WebHost,最终生成宿主。
var host = CreateHostBuilder(args).Build();

Expand Down Expand Up @@ -72,11 +64,15 @@ public static void Main(string[] args)
.UseStartup<Startup>()
.ConfigureLogging((hostingContext, builder) =>
{
builder.ClearProviders();
builder.SetMinimumLevel(LogLevel.Trace);
builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
builder.AddConsole();
builder.AddDebug();
//该方法需要引入Microsoft.Extensions.Logging名称空间
builder.AddFilter("System", LogLevel.Error); //过滤掉系统默认的一些日志
builder.AddFilter("Microsoft", LogLevel.Error);//过滤掉系统默认的一些日志
//添加Log4Net
//var path = Directory.GetCurrentDirectory() + "\\log4net.config";
//不带参数:表示log4net.config的配置文件就在应用程序根目录下,也可以指定配置文件的路径
//需要添加nuget包:Microsoft.Extensions.Logging.Log4Net.AspNetCore
builder.AddLog4Net();
});
});
}
Expand Down
Loading

0 comments on commit ecaffb6

Please sign in to comment.