In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to use Serilog to replace Log4j". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to replace Log4j with Serilog".
Why use Serilog
Serilog is an open source logging library for .NET applications with simple configuration, clean interface, and can run on the latest .NET platform. Unlike other log libraries, Serilog is built on the basis of powerful structured event data, supporting the output of logs to the console, files, databases and other ways, parameterized log templates are supported, and are very flexible.
Before our project uses Log4j to record user logs, in the process of development, slowly found that Log4j does not seem to meet our needs, such as structure, log analysis, etc., so we decided to use serilog to replace Log4j, in the use of the process found that Serilog is still very powerful.
Delete the original Log4j
1. Uninstall the log4j package
two。 Delete the log4j folder
3. Delete the code for startup
4. Delete log4j-related code
Install the Serilog package
Nuget installs the following packages
Configure Serilog
Edit Appsetting.json
"Serilog": {"MinimumLevel": {"Default": "Debug", / / minimum logging level "Override": {/ / minimum logging level "Default": "Warning", "System": "Warning", "Microsoft": "Warning"}} "WriteTo": [{"Name": "Console"} / / output to console]}
Program.cs replaces the system's logger with serilog
Public static IHostBuilder CreateHostBuilder (string [] args) = > Host.CreateDefaultBuilder (args) .UseServiceProviderFactory (new AutofacServiceProviderFactory ()) / / {webBuilder.UseStartup () .UseSerilog ((context, logger) = > / / register Serilog {logger.ReadFrom.Configuration (context.Configuration)) Logger.Enrich.FromLogContext ();})
The Test controller injects logger and modifies the LogTest method.
Private readonly ILogger _ logger; public TestController (ILogger logger) {_ logger = logger;} / [HttpGet] public IActionResult LogTest () {/ / _ logger.Error (typeof (TestController), "this is the error log", new Exception ("123")) / / _ logger.Debug (typeof (TestController), "this is the bug log"); / / throw new System.IO.IOException (); _ logger.LogInformation ("info log"); _ logger.LogDebug ("debug log"); _ logger.LogError (new System.IO.IOException (), "io error"); return Ok ();}
You can see that the log is output to the console
Configure Serilog output to a file
Appsetting.json add configuration
"WriteTo": [{"Name": "Console"}, / / output to the console {"Name": "Async", / / Serilog.Sinks.Async "Args": {"configure": [{"Name": "File" / / output file "Args": {"path": "log/log.txt", "outputTemplate": "{NewLine} Date: {Timestamp:yyyy-MM-dd HH:mm:ss.fff} {NewLine} LogLevel: {Level} {NewLine} Message: {Message} {NewLine} {Exception}" "rollingInterval": "3" / / record by day}}]}}]
Start the project test
A log file is generated
Output to the database
Configure Serilog output to database
Appsetting.json configuration
{"Name": "Async", / / Serilog.Sinks.Async "Args": {"configure": [{"Name": "File", / / output file "Args": {"path": "log/log.txt" "outputTemplate": "{NewLine} Date: {Timestamp:yyyy-MM-dd HH:mm:ss.fff} {NewLine} LogLevel: {Level} {NewLine} Message: {Message} {NewLine} {Exception}", "rollingInterval": "3" / / Daily record}}, "Name": "MSSqlServer" / / output to sqlserver "connectionString": "Server=." User Id=sa;Password=sa123;Database=ApiLog MultipleActiveResultSets=true "," schemaName ":" dbo ", / / database owner Default dbo "tableName": "Logs", / / the name of the log table "autoCreateSqlTable": true, / / whether to automatically create the table "restrictedToMinimumLevel": "Information", / / the minimum level "batchPostingLimit": 100 for logging / / the maximum number of logs submitted in a single batch processing: "period": "0.00true 0030", / / interval between batch submissions "columnOptionsSection": {"disableTriggers": true, "clusteredColumnstoreIndex": false, "primaryKeyColumnName": "Id" "addStandardColumns": ["LogEvent"], "removeStandardColumns": ["MessageTemplate"], "additionalColumns": [/ / Custom columns {"ColumnName": "Ip", "DataType": "varchar" "DataLength": 20}, "ColumnName": "UserName", "DataLength": 30 "ColumnName": "UserId", "DataLength": 50 "ColumnName": "LogType" "DataType": "tinyint"ColumnName": "Parameter"ColumnName": "Result"}], "id": {"nonClusteredIndex": true} "properties": {"columnName": "Properties", "excludeAdditionalProperties": true, "dictionaryElementName": "dict", "itemElementName": "item", "omitDictionaryContainerElement": false, "omitSequenceContainerElement": false "omitStructureContainerElement": false, "omitElementIfEmpty": true, "propertyElementName": "prop", "rootElementName": "root", "sequenceElementName": "seq", "structureElementName": "struct" "usePropertyKeyAsElementName": false}, "timeStamp": {"columnName": "Timestamp", "convertToUtc": true "logEvent": {"excludeStandardColumns": true "message": {"columnName": "message"} "exception": {"columnName": "exception"}
The Test controller modifies the Aoptest method by adding the following statement
_ logger.LogInformation ("ip: {IP}, username {UserName}, userid: {UserId}", "127.0.0.1", "admin", "1")
Start the project, test the interface, and the database has been inserted.
Configure Serilog output to Seq
The Seq component, which shows the log in the form of web page UI, has more diversified contents and gives more functions to log search.
First, install the Seq component, Seq download address: https://getseq.net/Download
It is free to use in the local development case, and a commercial license is required if you need to use it in a production environment (you know, money). In the current version, 4.2 can only run under windows, that is, if we are developed under windows, we can use this convenient to view the log information during testing and follow the given installation steps to complete the installation.
After the installation is complete, the browser outputs localhost:5341 and you will see the following page
Appsetting.json configuration output to seq
{"Name": "Seq", / / output to seq "Args": {"serverUrl": "http://192.168.0.89:5341"}}"
Start the project, test the interface, and you can see the data through the page.
Logging using Serilog globally
In CustomExceptionMiddleware.cs, just like this.
Public class CustomExceptionMiddleware {private readonly RequestDelegate _ next; private readonly ILogger _ logger; public CustomExceptionMiddleware (RequestDelegate next, ILogger logger) {_ next = next;} public async Task Invoke (HttpContext httpContext) {try {await _ next (httpContext) } catch (Exception ex) {_ logger.LogError (ex.Message, ex); / / logging await HandleExceptionAsync (httpContext, ex.Message);}
The same is true in GlobalExceptionsFilter
Public class GlobalExceptionsFilter: IExceptionFilter {private readonly IHostEnvironment _ env; private readonly ILogger _ logger; public GlobalExceptionsFilter (IHostEnvironment env, ILogger logger) {_ env = env; _ logger = logger;} public void OnException (ExceptionContext context) {var json = new JsonErrorResponse (); json.Message = context.Exception.Message / / error message if (_ env.IsDevelopment ()) {json.DevelopmentMessage = context.Exception.StackTrace;// stack information} context.Result = new InternalServerErrorObjectResult (json); _ logger.LogError (context.Exception, context.Exception.Message);}
Install this package if you want to use it in the service layer or warehouse
And then use it directly in the code.
Thank you for your reading, the above is the content of "how to use Serilog to replace Log4j". After the study of this article, I believe you have a deeper understanding of how to use Serilog to replace Log4j, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.