.Net Core 8 NLog连接PostgreSQL数据库
最近在做的项目需要把日志记录到本地和数据库,我使用的是NLog,主要参考博文链接:.NET项目中NLog的配置与使用 - 追逐时光者 - 博客园,下面是NLog连接PostgreSQL数据库的步骤,网上关于NLog连接PostgreSQL数据库的实例比较少,大多数都是mysql的。
1、创建Nlog.config配置文件,将下面配置文件内容复制进去,里面包含了存储数据库和本地。
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
>
<targets>
<target xsi:type="Database"
name="pgsql"
dbProvider="Npgsql.NpgsqlConnection,Npgsql"
connectionString="database=postgres;server=localhost;port=5432;user id=postgres;password=123456;">
<commandText>
INSERT INTO syslog (machineName, logged, level, message,logger, callSite, exception)
VALUES (@machineName, @logged, @level, @message, @logger, @callSite, @exception)
</commandText>
<parameter name="@machineName" layout="${machinename}"/>
<parameter name="@logged" layout="${date}"/>
<parameter name="@level" layout="${level}"/>
<parameter name="@message" layout="${message}"/>
<parameter name="@logger" layout="${logger}"/>
<parameter name="@callSite" layout="${callsite}"/>
<parameter name="@exception" layout="${exception:tostring}"/>
</target>
<target name="asyncFile" xsi:type="AsyncWrapper">
<!--项目日志保存文件路径说明fileName="${basedir}/保存目录,以年月日的格式创建/${shortdate}/${记录器名称}-${单级记录}-${shortdate}.txt"-->
<target name="log_file" xsi:type="File"
fileName="${basedir}/ProjectLogs/${shortdate}/${logger}-${level}-${shortdate}.txt"
layout="${longdate} | ${message} ${onexception:${exception:format=message} ${newline} ${stacktrace} ${newline}"
archiveFileName="${basedir}/archives/${logger}-${level}-${shortdate}-{#####}.txt"
archiveAboveSize="102400"
archiveNumbering="Sequence"
concurrentWrites="true"
keepFileOpen="false" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="pgsql"/>
<logger name="Microsoft.*" minlevel="Info" writeTo="" final="true" />
<logger name="*" minlevel="Info" writeTo="asyncFile" />
<logger name="*" minlevel="Warn" writeTo="colorConsole" />
</rules>
</nlog>
2、安装nuget包
- NLog
- NLog.Database
- Npgsql
3、创建LoggerHelper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | /// <summary> /// nLog使用帮助类 /// </summary> public class LoggerHelper { /// <summary> /// 实例化nLog,即为获取配置文件相关信息(获取以当前正在初始化的类命名的记录器) /// </summary> private readonly NLog.Logger _logger = LogManager.GetCurrentClassLogger(); private static LoggerHelper _obj; public static LoggerHelper Logger { get => _obj ?? ( new LoggerHelper()); set => _obj = value; } #region Debug,调试 public void Debug( string msg) { _logger.Debug(msg); } public void Debug( string msg, Exception err) { _logger.Debug(err, msg); } #endregion #region Info,信息 public void Info( string msg) { _logger.Info(msg); } public void Info( string msg, Exception err) { _logger.Info(err, msg); } #endregion #region Warn,警告 public void Warn( string msg) { _logger.Warn(msg); } public void Warn( string msg, Exception err) { _logger.Warn(err, msg); } #endregion #region Trace,追踪 public void Trace( string msg) { _logger.Trace(msg); } public void Trace( string msg, Exception err) { _logger.Trace(err, msg); } #endregion #region Error,错误 public void Error( string msg) { _logger.Error(msg); } public void Error( string msg, Exception err) { _logger.Error(err, msg); } #endregion #region Fatal,致命错误 public void Fatal( string msg) { _logger.Fatal(msg); } public void Fatal( string msg, Exception err) { _logger.Fatal(err, msg); } #endregion |
4、生成日志记录表
1 2 3 4 5 6 7 8 9 | CREATE TABLE public .syslog ( machinename varchar (50) NOT NULL , "logged" varchar (50) NOT NULL , "level" varchar (50) NOT NULL , message text NOT NULL , logger varchar (250) NULL , callsite text NULL , "exception" text NULL ); |
5、在你需要记录日志的地方调用
1 | LoggerHelper.Info( "测试" ) |
项目源码地址:https://github.com/cplmlm/ManagementSystem、https://gitee.com/cplmlm/ManagementSystem
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?