zoukankan      html  css  js  c++  java
  • 一个不需要Log4Net的写日志的简单方法

    有些项目写日志时会选择大名鼎鼎的Log4Net。而在我们使用它时,总会出现一些诸如版本不匹配而造成的写日志失败的情况,还要改web.config,还要改AssemblyInfo。而且,它的失败,并不是以日志的形式展现,而是“无反应”,你无法知道是哪里出了问题,最终的效果就是“没有输出日志且不知道为什么,需要根据百度和经验判断”。索性放弃。我只是要输出文本日志而已,杀鸡不要用牛刀了。

    以下是一个简单实用的日志类,无需配置。

     1 using System;
     2 using System.Collections.Generic;
     3 using System.IO;
     4 using System.Linq;
     5 using System.Text;
     6 using System.Web;
     7 
     8 namespace  Common
     9 {
    10    public class LogHelper
    11     {
    12 
    13        /// <summary>
    14        /// 写入日志
    15        /// </summary>
    16         ///  <param name="action">日志说明</param>
    17        /// <param name="msg">内容</param>
    18         public static void WriteLog(string action,string msg)
    19         {
    20             string sj=DateTime.Now.ToString("yyyyMMdd");
    21             string logFileName = action+sj+ ".txt";
    22 
    23 
    24            string logPath = HttpContext.Current.Server.MapPath("~/Log/"+sj+"");
    25             string fullPath = logPath + @"" + logFileName;
    26             
    27             if (!Directory.Exists(logPath))
    28             {
    29                 Directory.CreateDirectory(logPath);
    30             }
    31             using (StreamWriter writer = File.AppendText(fullPath))
    32             {
    33                 Log(msg, writer);
    34                 writer.Close();
    35             }
    36         }
    37         private static void Log(string logMessage, TextWriter writer)
    38         {
    39             writer.Write("
    Log Entry : ");
    40             writer.WriteLine("{0} {1} :", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString());
    41             writer.WriteLine(" {0}", logMessage);
    42             writer.WriteLine("-------------------------------");
    43             writer.Flush();
    44         }
    45     }
    46 }
  • 相关阅读:
    算法训练 区间k大数查询
    算法训练 最大最小公倍数
    身份证号码升级
    python包与模块导入
    python函数
    HDU 3595 博弈论,被支配的恐惧
    BZOJ 3195 [Jxoi2012]奇怪的道路
    大暑假集训
    [Poi2010]Monotonicity 2
    BZOJ 4868 HEOI 期末考试
  • 原文地址:https://www.cnblogs.com/apeng/p/12941121.html
Copyright © 2011-2022 走看看