首页 > 编程语言 >C#_LOG的使用,工具类

C#_LOG的使用,工具类

时间:2022-09-03 18:34:12浏览次数:59  
标签:Info LOG C# static Msg 工具 public string

1、NLog

导包

包名:NLog.Extensions.Logging

配置文件

创建配置文件,使用默认名字nlog.config,会减少很多不必要的麻烦

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/nlog.xsd"
      xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
      xsi:schemalocation="http://www.nlog-project.org/schemas/nlog.xsd nlog.xsd"
      autoreload="true"
      throwexceptions="false"
      internalloglevel="off" internallogfile="c:\temp\nlog-internal.log">

	<!-- optional, add some variables
  https://github.com/nlog/nlog/wiki/configuration-file#variables
  -->
	<!--
  <variable name="myvar" value="myvalue"/>
    -->
	<variable name="fileformat"
            value="
			${newline}date:${date}
            ${newline}level:${level}
            ${newline}machinename:${machinename}
            ${newline}message:${message}
            ${newline}appdomain:${appdomain}
            ${newline}processname:${processname}
            ${newline}stacktrace: ${stacktrace}
            ${newline}------------------------------------------------------------" />

	<!--see https://github.com/nlog/nlog/wiki/configuration-file 
	for information on customizing logging rules and outputs.
	-->
	<targets>

		<!--
    add your targets here
    see https://github.com/nlog/nlog/wiki/targets for possible targets.
    see https://github.com/nlog/nlog/wiki/layout-renderers for the possible layout renderers.
    -->

		<!--
    write events to a file with the date in the filename.
    <target xsi:type="file" name="f" filename="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->

		<target name="file" xsi:type="file"
			  filename="${basedir}/logs/${date:format=yyyy-MM}/${shortdate}/${date:format=yyyy-MM-dd HH}.log"
			  layout="${fileformat}"
			  maxarchivefiles="24"
			  archiveabovesize="1024000"
			  archiveevery="day"/>

	</targets>

	<rules>
		<!-- add your logging rules here -->

		<!--
    write all events with minimal level of debug (so debug, info, warn, error and fatal, but not trace)  to "f"
    <logger name="*" minlevel="debug" writeto="f" />
    -->

		<!--
        level    example
        fatal    highest level: important stuff down
        error    for example application crashes / exceptions.
        warn    incorrect behavior but the application can continue
        info    normal behavior like mail sent, user updated profile etc.
        debug    executed queries, user authenticated, session expired
        trace    begin method x, end method x etc
    -->
		<!--
        logging 水平分为以下等级“trace<<debug<<info<<warn<<error<<fatal ”,如果我们选择info值,则trace和debug等级的信息不会被输出。
    -->
		<logger name="*" minlevel="trace" writeto="file"/>
	</rules>
</nlog>

封装类

//日志级别:Trace->Debug->Information->Warning->Error->Critical(Fatal),级别包含范围由大到小 ,如 Trace 就包含了所有信息。
public class LogTool
{
    private static readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

    /// <summary>
    /// 五级LOG
    /// </summary>
    /// <param name="Msg"></param>
    public static void Trace(string Msg)
    {
        _logger.Trace(Msg);
    }

    /// <summary>
    /// 四级LOG
    /// </summary>
    /// <param name="Msg"></param>
    public static void Debug(string Msg)
    {
        _logger.Debug(Msg);
    }

    /// <summary>
    /// 三级LOG
    /// </summary>
    /// <param name="Msg"></param>
    public static void Info(string Msg)
    {
        _logger.Info(Msg);
    }

    /// <summary>
    /// 三级LOG
    /// </summary>
    /// <param name="Msg"></param>
    public static void Warning(string Msg)
    {
        _logger.Warn(Msg);
    }

    /// <summary>
    /// 二级LOG
    /// </summary>
    /// <param name="Msg"></param>
    public static void Error(string Msg)
    {
        _logger.Error(Msg);
    }

    /// <summary>
    /// 一级LOG
    /// </summary>
    /// <param name="Msg"></param>
    public static void Fatal(string Msg)
    {
        _logger.Fatal(Msg);
    }
}

2、Log4net

导包

包名:LoggerUtils

配置文件

文件名称使用log4net.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
  </configSections>
  <log4net debug="false">
    <!-- 将日志信息写入到项目日志文件 -->
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <encoding value="utf-8" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <file value="D:/Logs/" />
      <datePattern value="yyyyMMdd'.log'" />
      <staticLogFileName value="false" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="50MB" />
      <layout type="log4net.Layout.PatternLayout">
        <ConversionPattern value="%date 线程ID:[%thread] 日志级别:%-5level - 描述:%message %newline" />
        <!--<ConversionPattern value="%date 线程ID:[%thread] 日志级别:%-5level 相关类:%logger property:[%property{NDC}] - 描述:%message %newline" />-->
      </layout>
    </appender>
    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="ERROR" />
        <foreColor value="Red, HighIntensity" />
      </mapping>
      <mapping>
        <level value="Info" />
        <foreColor value="Green" />
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] [%-5level] %m %n" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="Info" />
        <param name="LevelMax" value="Fatal" />
      </filter>
    </appender> 
    <appender name="RollingFileAppenderCustomName" type="log4net.Appender.RollingFileAppender">
      <encoding value="utf-8" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <file value="D:/Logs/CustomName/" />
      <datePattern value="yyyyMMdd'.log'" />
      <staticLogFileName value="false" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="50MB" />
      <layout type="log4net.Layout.PatternLayout">
        <ConversionPattern value="%date 线程ID:[%thread] 日志级别:%-5level - 描述:%message %newline" />
        <!--<ConversionPattern value="%date 线程ID:[%thread] 日志级别:%-5level 相关类:%logger property:[%property{NDC}] - 描述:%message %newline" />-->
      </layout>
    </appender>

    <!--设置根目录,添加appenders并设置默认日志等级 -->
    <root>
      <level value="All" />
      <!--<appender-ref ref="ADONetAppender" />-->
      <appender-ref ref="RollingFileAppender"/>
      <appender-ref ref="ColoredConsoleAppender"/>
    </root>
    <logger name="CustomName" additivity="false">
      <level value="All" />
      <appender-ref ref="RollingFileAppenderCustomName"/>
    </logger>
  </log4net>
</configuration>

封装类

使用方法:开启和终结日志的使用方法WriteLogStartOrEnd,中间记录统一使用WriteLogToFile

/// <summary>
/// 开启或终结日志
/// </summary>
///<param name="StartOrEnd">开启(START),终结(END)</param>
/// <returns></returns>
public static bool WriteLogStartOrEnd(string StartOrEnd)
{
    string strFlag = StartOrEnd.ToUpper();
    try
    {
        switch (strFlag)
        {
            case "START":
                Log4netHelper.Register(@"D:\LogInfo\SendEDIData\");//记录Log,放到本地D盘LogInfo文件夹下的Tea文件夹
                Log4netHelper.Instance.Info("===============================================================");
                Log4netHelper.Instance.Info("开始执行任务");
                break;
            case "END":
                Log4netHelper.Instance.Info("执行完成");
                Log4netHelper.Instance.Info("==============================================================");
                break;
            default:
                Log4netHelper.Instance.Info("开始或结束失败,输入START或END标识有错");
                break;
        }
        return true;
    }
    catch (Exception ex)
    {
        //邮件
        SendEMailBySite("【编号】" + strFlag + "日志失败", ex.Message.ToString());
        return false;
    }
}

/// <summary>
/// 记录日志到本地文件中
/// </summary>
/// <param name="Msg">日志内容</param>
/// <returns></returns>
public static bool WriteLogToFile(string Msg)
{
    try
    {
        Log4netHelper.Instance.Info(Msg);
        return true;
    }
    catch (Exception ex)
    {
        //发邮件
        SendEMailBySite("【编号】记录log失败",ex.Message.ToString());
        return false;
    }
}

标签:Info,LOG,C#,static,Msg,工具,public,string
From: https://www.cnblogs.com/diffknow/p/16653281.html

相关文章

  • Docker日常工作常用命令
    容器生命周期管理Docker创建新容器并运行[run]语法:dockerrun[OPTIONS]IMAGE[COMMAND][ARG...]OPTIONS说明:-astdin:指定标准输入输出内容类型,可选STDIN/STDOU......
  • docker安装awvs
    前提:安装了docker ➊docker中拉取下载镜像dockerpullsecfa/docker-awvs➋将docker的3443端口映射到物理机的13443端口dockerrun-it-d-p13443:3443secfa/dock......
  • ASP.NET Core 实战-10.使用依赖注入的服务配置
    依赖注入简介本节旨在让您基本了解什么是依赖注入,为什么要关注它,以及ASP.NETCore如何使用它。该主题本身远远超出了这一章的范围。如果您想要更深入的背景,我强烈建议......
  • ASP.NET Core 实战-8.使用标签助手构建表单
    显示动态数据是许多Web应用程序的一个重要方面,但它通常只是故事的一半。除了向用户显示数据之外,您通常还需要用户能够将数据提交回您的应用程序。例如,您可以使用数据来......
  • C#/.net面试知识点总结
    &和&&的区别相同点&和&&都可作逻辑与的运算符,表示逻辑与(and),当运算符两边的表达式的结果都为true时,其结果 才为true,否则,只要有⼀⽅为false,则结果为false。(ps:当要⽤到逻辑......
  • typeof 和 instanceof 判断值类型
    两者的作用typeof运算符能区分原始值和对象,并检测出原始值的类型。instanceof运算符可以检测一个对象是否是特定构造函数的一个实例。typeof值结果undefi......
  • Eclipse配置Tomcat搭建java Web (JSP)开发环境
    配置Tomcat服务1.打开窗口-首选项-Server-RuntiomeEnvironments2.点击ADD,选择对应的Tomcat版本,点击下一步路径选择Tomcat解压后的文件夹目录,点击完成并保存创建动......
  • ASP.NET Core 实战-6.绑定模型:检索和验证用户输入
    理解RazorPages和MVC中的模型MVC就是关注点分离。前提是通过隔离应用程序的每个方面以专注于单一职责,它可以减少系统中的相互依赖性。这种分离使得在不影响应用程......
  • XCPC集训48
    A-SquareString?/* qwq!*/#include<iostream>#include<algorithm>#include<cstring>#include<cstdio>#include<map>#include<vector>#include<queue>......
  • leetcode 77 组合 C/C++ 深度优先搜索
    #include<iostream>#include<vector>usingnamespacestd;classSolution{public:voidrecursive(intn,intk,intvalue,intindex,vector<int>&com_case,ve......