美文网首页
添加日志功能

添加日志功能

作者: 张中华 | 来源:发表于2018-07-24 23:06 被阅读103次

一个网站没有日志也是很糟糕的一件事情,在此使用Nlog添加一个log帮助类,由于是在测试,所以只写了debug和info两个种方法,其他的在之后添加,有些Nlog提供的其他方法,在有需要的时候再另外添加:
1.类代码:

using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyBlogNew.Common
{
    public class LoggerHelper
    {
        public enum LogLevel
        {
            Trace,
            Debug,
            Info,
            Error,
            Fatal
        }
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public static void Info(string message)
        {
            if (string.IsNullOrEmpty(message))
                return;
            logger.Info(message);
        }
        public static void Info(string message, Exception ex)
        {
            if (string.IsNullOrEmpty(message))
                return;
            logger.Info(ex,message);
        }

        public static void Debug(string message)
        {
            if (string.IsNullOrEmpty(message))
                return;
            logger.Debug(message);
        }
        public static void Debug(string message, Exception ex)
        {
            if (string.IsNullOrEmpty(message))
                return;
            logger.Debug(ex,message);
        }
    }
}

2.配置文件

<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />   
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>f
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="None" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>
    <!--
            If you are deploying to a cloud environment that has multiple web server instances,
            you should change session state mode from "InProc" to "Custom". In addition,
            change the connection string named "DefaultConnection" to connect to an instance
            of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
      -->
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v13.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"></provider>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target name="console" xsi:type ="Console" />
      <target name="debugger" xsi:type="Debugger" layout="${date:format=HH\:mm\:ss.fff}: ${message}" />
      <target name="error_file" xsi:type="File"
                      fileName="${basedir}/Logs/Error/${shortdate}/error.txt" maxArchiveFiles="30"
                      layout="${longdate} | ${level:uppercase=false} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
      <target name="info" xsi:type="File"
                  fileName="${basedir}/Logs/info/${shortdate}/info.txt" maxArchiveFiles="30"
                  layout="${longdate} | ${level:uppercase=false} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
    </targets>

    <rules>
      <logger name="*" writeTo="console" />
      <logger name="*" minlevel="Debug" writeTo="debugger" />
      <logger name="*" minlevel="Error" writeTo="error_file" />
      <logger name="*" level="Info" writeTo="info" />
    </rules>
  </nlog>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>
  1. 编写方法测试:
 public int GetDiariesTotalNumOne()
        {
            try
            {
                using (var entity = new MyBlogNewEntities())
                {
                    int totalPage = entity.Diaries.ToList().Count();

                    LoggerHelper.Info("hello");
                    Dictionary<int, string> map = new Dictionary<int, string>();
                    map.Add(1,"hello");
                    map.Add(1,"world");
                    return totalPage;
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Info("hello",ex);
                return 0;
            }
        }

4.测试结果
可以看出返回结果为0


再查看日志内容:



此处可以看出,从Logs文件夹开始,都是可以在配置文件中进行配置的。
日志内容:


2018-07-24 23:02:35.7240 | Info | hello
2018-07-24 23:02:35.9280 | Info | hello System.ArgumentException: 已添加了具有相同键的项。
在 System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
在 System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) 在 System.Collections.Generic.Dictionary2.Add(TKey key, TValue value)
在 MyBlogNew.Controllers.DiaryController.GetDiariesTotalNumOne() 位置 f:\MyBlogNew\MyBlogNewApi\MyBlogNew\Controllers\DiaryController.cs:行号 63
<no type>.lambda_method => DiaryController.GetDiariesTotalNumOne => LoggerHelper.Info

公众号.png

相关文章

  • 添加日志功能

    一个网站没有日志也是很糟糕的一件事情,在此使用Nlog添加一个log帮助类,由于是在测试,所以只写了debug和i...

  • 日志跟踪

    日志功能添加 if not os.path.exists('../log'):os.makedirs('../lo...

  • Spring Boot 11 -- 日志功能

    一、说明 使用 slf4j 和 logback 完成日志功能 二、添加依赖 三、在 resources 下添加配置...

  • 简单的 Golang 多色日志包

    比较简约的多色日志包,没有特别多的功能,仅提供在终端输出彩色日志的功能。 使用 在go.mod文件中添加log包:...

  • 3.HTTPD实现多虚拟主机

    目录:1.统计日志访问量2.添加加密模块3.添加压缩功能4.多虚拟主机 1.统计日志访问量 2.添加加密模块 3....

  • spring boot日志系统

    简介 本博客介绍了springBoot的日志部分功能 在pom文件中引入maven依赖 配置文件添加日志信息 在r...

  • Spring Aop - 初识

    常见名词解释通知、增强处理(Advice) : 代表你通过切面想要给目标方法添加的功能。常见的如:日志功能,方法用...

  • SSM之SSM应用实例

    一 日志功能,实现将用户操作日志保存到数据库 1.准备工作 新建ssm项目,添加依赖,在spring-mvc.xm...

  • Mysql 使用binlog日志 通过时间点或位置点的恢复

    开启 mysql binlog 日志功能 vim /etc/my.cnf 添加下面内容 重启mysql 全量备份m...

  • asp.net core 使用 NLog日志

    NLog是一个配置灵活的日志记录类库,拥有输出日志到文件、存储入库、发送到udp地址的高级功能 1 添加 nlog...

网友评论

      本文标题:添加日志功能

      本文链接:https://www.haomeiwen.com/subject/qtkumftx.html