为App添加Log日志文件

 

using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace app.Lib
{
    public enum Level
    {
        Debug,
        Exception,
        Info,
        Warn,
    }

    public enum Priority
    {
        None,
        High,
        Medium,
        Low,
    }
    public class Logger
    {
        private static StreamWriter _writer;
        //private static string _format = "{1}: {2}. Priority: {3}. Timestamp:{0:u}";
        private static string _format = "{0:u}:{1:D3}  {2}:   {3}";
        private static StreamWriter Writer
        {
            get
            {
                if (_writer == null)
                {
                    string path = Application.StartupPath + "//Log//" + DateTime.Now.ToString("yyyy") + "//" +
                          DateTime.Now.ToString("yyyyMM") + "//" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";
                    string filepath = Application.StartupPath + "//Log//" + "//bmp//";

                    string dir = Path.GetDirectoryName(path);
                    string filedir = Path.GetDirectoryName(filepath);

                    if (filedir != null && !Directory.Exists(filedir))
                    {
                        Directory.CreateDirectory(filedir);
                    }

                    if (dir != null && !Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    _writer = new StreamWriter(path, true, Encoding.Default);
                    _writer.AutoFlush = true;
                }
                return _writer;
            }
        }

        public static string GetFileDirName()
        {
            return Application.StartupPath + "//Log" + "//bmp//";
        }

        public static void Log(string message, Level level)
        {
            string messageToLog = String.Format(CultureInfo.InvariantCulture, _format, DateTime.Now, DateTime.Now.Millisecond,
                level.ToString().ToUpper(CultureInfo.InvariantCulture), message);

            Writer.WriteLine(messageToLog);
        }

        public static bool EnableLog;
    }
}
View Code

 

 

很多时候需要为我们应用程序添加日子文件,方便问题定位

代码转载而来,非原创

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.IO;
  6 using System.Reflection;
  7 
  8 namespace CommonLib
  9 {
 10     /// <summary>
 11     /// 日志类型
 12     /// </summary>
 13     public enum LogType
 14     {
 15         All,
 16         Information,
 17         Debug,
 18         Success,
 19         Failure,
 20         Warning,
 21         Error
 22     }
 23 
 24 
 25     public class Logger
 26     {
 27 
 28         #region Instance
 29         private static object logLock;
 30 
 31         private static Logger _instance;
 32 
 33         private static string logFileName;
 34         private Logger() { }
 35 
 36         /// <summary>
 37         /// Logger instance
 38         /// </summary>
 39         public static Logger Instance
 40         {
 41             get
 42             {
 43                 if (_instance == null)
 44                 {
 45                     _instance = new Logger();
 46                     logLock = new object();
 47                     //logFileName = Guid.NewGuid() + ".log";
 48                     logFileName = DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") +DateTime.Now.Second.ToString("00") + ".log";
 49                 }
 50                 return _instance;
 51             }
 52         }
 53         #endregion
 54 
 55         /// <summary>
 56         /// Write log to log file
 57         /// </summary>
 58         /// <param name="logContent">Log content</param>
 59         /// <param name="logType">Log type</param>
 60         public void WriteLog(string logContent, LogType logType = LogType.Information, string fileName = null)
 61         {
 62             try
 63             {
 64                 string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
 65                 basePath = Directory.GetCurrentDirectory(); //@"C:\APILogs";
 66                 if (!Directory.Exists(basePath + "\\Log"))
 67                 {
 68                     Directory.CreateDirectory(basePath + "\\Log");
 69                 }
 70 
 71                 string dataString = DateTime.Now.ToString("yyyy-MM-dd");
 72                 if (!Directory.Exists(basePath + "\\Log\\" + dataString))
 73                 {
 74                     Directory.CreateDirectory(basePath + "\\Log\\" + dataString);
 75                 }
 76 
 77                 string[] logText = new string[] { DateTime.Now.ToString("hh:mm:ss") + ": " + logType.ToString() + ": " + logContent };
 78                 if (!string.IsNullOrEmpty(fileName))
 79                 {
 80                     fileName = fileName + "_" + logFileName;
 81                 }
 82                 else
 83                 {
 84                     fileName = logFileName;
 85                     //fileName = DateTime.Now.ToString("hh:mm:ss");
 86                 }
 87 
 88                 lock (logLock)
 89                 {
 90                     File.AppendAllLines(basePath + "\\Log\\" + dataString + "\\" + fileName, logText);
 91                 }
 92             }
 93             catch (Exception) { }
 94         }
 95 
 96         /// <summary>
 97         /// Write exception to log file
 98         /// </summary>
 99         /// <param name="exception">Exception</param>
100         public void WriteException(Exception exception, string specialText = null)
101         {
102             if (exception != null)
103             {
104                 Type exceptionType = exception.GetType();
105                 string text = string.Empty;
106                 if (!string.IsNullOrEmpty(specialText))
107                 {
108                     text = text + specialText + Environment.NewLine;
109                 }
110                 text = "Exception: " + exceptionType.Name + Environment.NewLine;
111                 text += "               " + "Message: " + exception.Message + Environment.NewLine;
112                 text += "               " + "Source: " + exception.Source + Environment.NewLine;
113                 text += "               " + "StackTrace: " + exception.StackTrace + Environment.NewLine;
114                 WriteLog(text, LogType.Error);
115             }
116         }
117 
118     }
119 }
View Code

 

 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.IO;
  6 using System.Reflection;
  7 
  8 namespace CommonLib
  9 {
 10     /// <summary>
 11     /// 日志类型
 12     /// </summary>
 13     public enum LogType
 14     {
 15         All,
 16         Information,
 17         Debug,
 18         Success,
 19         Failure,
 20         Warning,
 21         Error
 22     }
 23 
 24 
 25     public class Logger
 26     {
 27 
 28         #region Instance
 29         private static object logLock;
 30 
 31         private static Logger _instance;
 32 
 33         private static string logFileName;
 34         private Logger() { }
 35 
 36         /// <summary>
 37         /// Logger instance
 38         /// </summary>
 39         public static Logger Instance
 40         {
 41             get
 42             {
 43                 if (_instance == null)
 44                 {
 45                     _instance = new Logger();
 46                     logLock = new object();
 47                     //logFileName = Guid.NewGuid() + ".log";
 48                     logFileName = DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") +DateTime.Now.Second.ToString("00") + ".log";
 49                 }
 50                 return _instance;
 51             }
 52         }
 53         #endregion
 54 
 55         /// <summary>
 56         /// Write log to log file
 57         /// </summary>
 58         /// <param name="logContent">Log content</param>
 59         /// <param name="logType">Log type</param>
 60         public void WriteLog(string logContent, LogType logType = LogType.Information, string fileName = null)
 61         {
 62             try
 63             {
 64                 string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
 65                 basePath = Directory.GetCurrentDirectory(); //@"C:\APILogs";
 66                 if (!Directory.Exists(basePath + "\\Log"))
 67                 {
 68                     Directory.CreateDirectory(basePath + "\\Log");
 69                 }
 70 
 71                 string dataString = DateTime.Now.ToString("yyyy-MM-dd");
 72                 if (!Directory.Exists(basePath + "\\Log\\" + dataString))
 73                 {
 74                     Directory.CreateDirectory(basePath + "\\Log\\" + dataString);
 75                 }
 76 
 77                 string[] logText = new string[] { DateTime.Now.ToString("hh:mm:ss") + ": " + logType.ToString() + ": " + logContent };
 78                 if (!string.IsNullOrEmpty(fileName))
 79                 {
 80                     fileName = fileName + "_" + logFileName;
 81                 }
 82                 else
 83                 {
 84                     fileName = logFileName;
 85                     //fileName = DateTime.Now.ToString("hh:mm:ss");
 86                 }
 87 
 88                 lock (logLock)
 89                 {
 90                     File.AppendAllLines(basePath + "\\Log\\" + dataString + "\\" + fileName, logText);
 91                 }
 92             }
 93             catch (Exception) { }
 94         }
 95 
 96         /// <summary>
 97         /// Write exception to log file
 98         /// </summary>
 99         /// <param name="exception">Exception</param>
100         public void WriteException(Exception exception, string specialText = null)
101         {
102             if (exception != null)
103             {
104                 Type exceptionType = exception.GetType();
105                 string text = string.Empty;
106                 if (!string.IsNullOrEmpty(specialText))
107                 {
108                     text = text + specialText + Environment.NewLine;
109                 }
110                 text = "Exception: " + exceptionType.Name + Environment.NewLine;
111                 text += "               " + "Message: " + exception.Message + Environment.NewLine;
112                 text += "               " + "Source: " + exception.Source + Environment.NewLine;
113                 text += "               " + "StackTrace: " + exception.StackTrace + Environment.NewLine;
114                 WriteLog(text, LogType.Error);
115             }
116         }
117 
118     }
119 }

 

转载于:https://www.cnblogs.com/fengbaobao/p/10751844.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值