C# Serilog配置和使用

1.安装NuGet安装
在这里插入图片描述

2.LogSerilog.cs类代码如下:
using Serilog;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormPro
{
public class LogSerilog
{
private LogSerilog(string name)
{
string SerilogOutputTemplate = “Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}” + new string(‘-’, 50) + “{NewLine}{NewLine}”;
log = new LoggerConfiguration().MinimumLevel.Debug()
.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Debug).WriteTo.Async(t => t.File( " L o g / n a m e / n a m e . l o g " , r o l l i n g I n t e r v a l : R o l l i n g I n t e r v a l . D a y , r e t a i n e d F i l e C o u n t L i m i t : 24 , b u f f e r e d : f a l s e , s h a r e d : t r u e , o u t p u t T e m p l a t e : S e r i l o g O u t p u t T e m p l a t e ) ) ) . W r i t e T

C#中,Serilog是一个强大的日志库,用于简化应用程序的日志记录过程。如果你想将它封装成一个DLL文件供其他项目引用调用,可以按照以下步骤操作: 1. **创建Serilog配置**: 首先,在主项目中设置好Serilog配置,包括 sinks(存储日志的地方),如控制台、文件、数据库等。确保这个配置在你的DLL不需要直接配置的情况下也能工作。 ```csharp using Serilog; using Serilog.Events; Log.Logger = new LoggerConfiguration() .WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}") .CreateLogger(); ``` 2. **编写公共API**: 创建一个公共类,包含你要封装的日志方法。这些方法应该是静态的,因为它们不需要访问实例状态。 ```csharp public static class LogWrapper { public static void Info(string message) => Log.Information(message); public static void Error(Exception exception) => Log.Error(exception, exception.Message); // 添加更多需要暴露给外部的方法 } ``` 3. **打包成DLL**: 使用Visual Studio或其他构建工具(如NuGet包管理器、 Paket、MSBuild等),创建一个新的Class Library项目,然后添加对Serilog的引用。将`LogWrapper`类及其依赖项导出到`PublicApi`命名空间,以便外部程序能够引用。 4. **发布引用**: 编译并发布DLL。在需要使用的项目中,通过NuGet或其他方式安装该DLL,并在引用中指定公开的命名空间。 现在,其他项目就可以像下面这样使用封装好的Serilog了: ```csharp using MyNamespace.Logging; // 引入你的DLL MyNamespace.Logging.LogWrapper.Info("This is an info log message."); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值