Nlog写入MySql

1.安装相关Nuget包

mysql.data,Nlog,Nlog.Database

2.新建配置文件,并右击配置文件修改属性 复制到输出目录-始终复制

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <nlog xmlns="http://www.nlog-project.org/schemas/nlog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

        <!--输出目标,往哪里输出-->
        <targets>
            <!--此部分中所有目标输出讲自动异步-->
            <default-wrapper xsi:type="AsyncWrapper"></default-wrapper>

            <!--type:日志输出类型 File:文件 ColoredConsole:控制台-->
            <!--fileName:日志存储的路径以及名称-->
            <!--archiveFileName:要用于存档的文件名称,可以指定日志-->
            <!--archiveAboveSize:以字节为单位的大小,超过该大小的日志文件将被自动存档-->
            <!--archiveNumbering:对未见的编号方式-->
            <!--concurrentWrites:当使用KeepFileOpen=true时,支持从同一主机上的多个进程优化并入统一日志文件,通过使用一种特殊的技术,可以让文件从多个进程打开,如果只有单个进程正在记录日志,那么设置为concurrentwrites=false会更快-->
            <!--keepfileOpen:指示是否每次记录事件是保持日志文件打开,将此属性更改为True将大大提高性能,同时也会保持文件句柄锁定。启动此选型时,请考虑设置OpenFileCacheTimeOut,因为它允许操作并对删除的日志文件做出反应-->
            <!--项目日志保存文件路径说明fileNmae="${basedir}/保存目录",以年月日的格式创建/${shortdata}/${记录名称}-${单位记录}-${shortdata}.txt-->

            <target name="info_file"
                    xsi:type="File"
                    fileName="${basedir}/logs/${shortdate}/log_all_${shortdate}.log"
                    layout="${longdate} | ${event-properties:item=EventId_Id:whenEmpty=0} | ${uppercase:${level}} | ${logger} | ${message} ${exception:format=tostring}"
                    archiveFileName="${basedir}/archives/${shortdate}/all_${shortdata}--{####}.log"
                    archiveAboveSize="102400"
                    archiveNumbering="Sequence"
                    concurrentWrites="true"
                    keepFileOpen="false"
                    />
            <target name="error_file"
                    xsi:type="File"
                    fileName="${basedir}/logs/${shortdate}/log_error_${shortdate}.log"
                    layout="${longdate} | ${event-properties:item=EventId_Id:whenEmpty=0} | ${uppercase:${level}} | ${logger} | ${message} ${exception:format=tostring}"
                    archiveFileName="${basedir}/archives/${shortdate}/error_${shortdata}--{####}.log"
                    archiveAboveSize="102400"
                    archiveNumbering="Sequence"
                    concurrentWrites="true"
                    keepFileOpen="false"
                    />

            <!--使用可自定义的着色将日志消息写入控制台-->
            <!-- <target name="console" xsi:type="ColoredConsole" layout="[${date:format=HH\:mm\:ss}]:${message} ${exception:format=message}" /> -->
            <target
                xsi:type="ColoredConsole"
                name="colorConsole"
                encoding="Encoding"
                detectConsoleAvailable="true"
                detectOutputRedirected="false"
                useDefaultRowHighlightingRules="false"
                header="--------------------"
                layout="${longdate}|${level:uppercase=true}|${logger}|${message}|${exception} ${newline} ${stacktrace} ${newline}"
                footer="---------------------"
        >
                <highlight-row condition="level == LogLevel.Trace" foregroundColor="DarkGray"/>
                <highlight-row condition="level == LogLevel.Debug" foregroundColor="DarkBlue"/>
                <highlight-row condition="level == LogLevel.Info" foregroundColor="White"/>
                <highlight-row condition="level == LogLevel.Warn" foregroundColor="DarkYellow"/>
                <highlight-row condition="level == LogLevel.Error" foregroundColor="Red"/>
                <highlight-row condition="level == LogLevel.Fatal" foregroundColor="DarkRed"/>
            </target>

            <!--将数据写入数据库-->
            <target xsi:type="Database" name="databaseTarget" 
                    dbProvider="MySql.Data.MySqlClient.MySqlConnection,MySql.Data"
                    connectionString="Server=localhost;Database=db_log;User Id=root;Password=123456;CharSet=utf8;">
                <commandText>
                    Insert into log(Date,Level,Message,Exception)Values(@time_stamp,@level,@message,@Exception);
                </commandText>
                <parameter name="@time_stamp" layout="${longdate}" />
                <parameter name="@level" layout="${level}" />
                <parameter name="@message" layout="${message:tostring}" />
                <parameter name="@Exception" layout="${exception:tostring}" />
            </target>

        </targets>

        <!--规则配置,final -最终规则匹配后不处理任何规则-->
        <!--定义使用那个target输出-->
        <rules>
            <!--优先级从高到低以此为:OFF/FATAL/ERROR/WARN/INFO/DEBUG/TRACE/ALL-->
            <!--将日志输出到文件-->
            <logger name="*" minlevel="Debug" writeTo="info_file"/>
            <logger name="*" minlevel="Warn" writeTo="error_file"/>
            <!-- 将所有日志输出到控制台  -->
            <logger name="*" minlevel="Debug" writeTo="colorConsole" />
            
            <!--将日志输出给数据库-->
            <logger name="*" minlevel="Debug" writeTo="databaseTarget" />
        </rules>
    </nlog>
</configuration>

 

 

出现相关文件解决

1.Nuget找不到任何文件

2.数据库写入报1252

  1. 问题原因
    • 在一些情况下,System.Text.Encoding.CodePages可能由于项目配置或 NuGet 包引用问题而无法找到。这可能是因为没有正确安装包含该命名空间的相关包,或者项目没有正确配置来使用这个组件。
  2. 解决方案
    • 安装 System.Text.Encoding.CodePages 包(如果适用)
      • 在某些.NET 版本中,System.Text.Encoding.CodePages是作为一个单独的 NuGet 包提供的。你可以通过以下步骤安装它:
      • 打开 Visual Studio,在解决方案资源管理器中右键单击你的项目,选择 “管理 NuGet 包”。
      • 在 “浏览” 选项卡中,搜索 “System.Text.Encoding.CodePages”。
      • 找到对应的包后,点击 “安装” 按钮,将其添加到你的项目中。
    • 检查.NET 版本和引用
      • 在.NET Core 和.NET 5 + 项目中,System.Text.Encoding.CodePages通常是作为System.Text.Encoding命名空间的一部分包含在内的。如果你的项目是基于这些较新的.NET 版本,可能是项目引用出现了问题。
      • 你可以尝试重新构建项目,确保所有的引用都正确解析。在 Visual Studio 中,可以通过 “生成” 菜单中的 “重新生成解决方案” 选项来执行此操作。
    • 在代码中注册编码提供程序(如果需要)
      • 有时候,即使包已经安装,你还需要在代码中显式地注册编码提供程序,以便能够使用特定的编码。例如:

      收起
      csharp
       
      System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
      

      • 这段代码应该在使用相关编码之前执行,它会注册编码提供程序,使得你可以使用例如CodePage编码等。例如,在读取使用特定代码页编码的文件时,这个步骤是很重要的。

 

通过以上步骤,应该可以解决在项目中找不到System.Text.Encoding.CodePages的问题
3.数据库写入中文???
在数据库连接是增加字符指定CharSet=utf8;
posted @ 2025-01-11 09:30  magic_d  阅读(36)  评论(0)    收藏  举报