记录webapi日志我使用了两种办法,一种是存储TXT的log文档,但我发现使用使用了我接口的日志都会存储到我电脑上。后面改用数据库存储log。数据库存储log信息这种方法个人比较推荐。之前花费了一些时间来写TXT存储还是想记录下来。

 

转载自:https://blog.csdn.net/lordwish/article/details/72353851

1、引用NLog类库

打开项目的NuGet包管理器,搜索NLog,为项目添加程序包引用。

 

webapi日志记录(TXT存储)

2、修改项目配置文件

在webAPI项目的Web.config中进行NLog的配置。首先在节点configuration>configSections下添加节点:

此处name必需为nlog,否则配置信息将不能被读取。 然后在configuration节点下添加节点nlog:

这里定义了日志文件的保存路径、命名格式以及日志记录类型和监听级别。

 注意:<configSections>必须要紧跟在<configuration>下方

<configuration>
   <configSections>
      <section name="nlog" type="NLog.Config.ConfigSectionHandler,NLog" />
    </configSections>

  <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema">
    <targets>
      <target name="logfile" xsi:type="File" fileName="${basedir}/LogFile/${date:format=yyyy/MM/dd}-api.txt"/>
      <target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source="Api Services"/>
    </targets>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="logfile"/>
      <logger name="*" minlevel="Trace" writeTo="eventlog"/>
    </rules>    
  </nlog>
</configuration>
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-25
  • 2022-12-23
  • 2021-05-29
  • 2022-12-23
  • 2021-12-27
猜你喜欢
  • 2021-11-26
  • 2022-12-23
  • 2021-10-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案