为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;
}
}

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

代码转载而来,非原创

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection; namespace CommonLib
{
/// <summary>
/// 日志类型
/// </summary>
public enum LogType
{
All,
Information,
Debug,
Success,
Failure,
Warning,
Error
} public class Logger
{ #region Instance
private static object logLock; private static Logger _instance; private static string logFileName;
private Logger() { } /// <summary>
/// Logger instance
/// </summary>
public static Logger Instance
{
get
{
if (_instance == null)
{
_instance = new Logger();
logLock = new object();
//logFileName = Guid.NewGuid() + ".log";
logFileName = DateTime.Now.Hour.ToString("") + DateTime.Now.Minute.ToString("") +DateTime.Now.Second.ToString("") + ".log";
}
return _instance;
}
}
#endregion /// <summary>
/// Write log to log file
/// </summary>
/// <param name="logContent">Log content</param>
/// <param name="logType">Log type</param>
public void WriteLog(string logContent, LogType logType = LogType.Information, string fileName = null)
{
try
{
string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
basePath = Directory.GetCurrentDirectory(); //@"C:\APILogs";
if (!Directory.Exists(basePath + "\\Log"))
{
Directory.CreateDirectory(basePath + "\\Log");
} string dataString = DateTime.Now.ToString("yyyy-MM-dd");
if (!Directory.Exists(basePath + "\\Log\\" + dataString))
{
Directory.CreateDirectory(basePath + "\\Log\\" + dataString);
} string[] logText = new string[] { DateTime.Now.ToString("hh:mm:ss") + ": " + logType.ToString() + ": " + logContent };
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName + "_" + logFileName;
}
else
{
fileName = logFileName;
//fileName = DateTime.Now.ToString("hh:mm:ss");
} lock (logLock)
{
File.AppendAllLines(basePath + "\\Log\\" + dataString + "\\" + fileName, logText);
}
}
catch (Exception) { }
} /// <summary>
/// Write exception to log file
/// </summary>
/// <param name="exception">Exception</param>
public void WriteException(Exception exception, string specialText = null)
{
if (exception != null)
{
Type exceptionType = exception.GetType();
string text = string.Empty;
if (!string.IsNullOrEmpty(specialText))
{
text = text + specialText + Environment.NewLine;
}
text = "Exception: " + exceptionType.Name + Environment.NewLine;
text += " " + "Message: " + exception.Message + Environment.NewLine;
text += " " + "Source: " + exception.Source + Environment.NewLine;
text += " " + "StackTrace: " + exception.StackTrace + Environment.NewLine;
WriteLog(text, LogType.Error);
}
} }
}
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection; namespace CommonLib
{
/// <summary>
/// 日志类型
/// </summary>
public enum LogType
{
All,
Information,
Debug,
Success,
Failure,
Warning,
Error
} public class Logger
{ #region Instance
private static object logLock; private static Logger _instance; private static string logFileName;
private Logger() { } /// <summary>
/// Logger instance
/// </summary>
public static Logger Instance
{
get
{
if (_instance == null)
{
_instance = new Logger();
logLock = new object();
//logFileName = Guid.NewGuid() + ".log";
logFileName = DateTime.Now.Hour.ToString("") + DateTime.Now.Minute.ToString("") +DateTime.Now.Second.ToString("") + ".log";
}
return _instance;
}
}
#endregion /// <summary>
/// Write log to log file
/// </summary>
/// <param name="logContent">Log content</param>
/// <param name="logType">Log type</param>
public void WriteLog(string logContent, LogType logType = LogType.Information, string fileName = null)
{
try
{
string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
basePath = Directory.GetCurrentDirectory(); //@"C:\APILogs";
if (!Directory.Exists(basePath + "\\Log"))
{
Directory.CreateDirectory(basePath + "\\Log");
} string dataString = DateTime.Now.ToString("yyyy-MM-dd");
if (!Directory.Exists(basePath + "\\Log\\" + dataString))
{
Directory.CreateDirectory(basePath + "\\Log\\" + dataString);
} string[] logText = new string[] { DateTime.Now.ToString("hh:mm:ss") + ": " + logType.ToString() + ": " + logContent };
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName + "_" + logFileName;
}
else
{
fileName = logFileName;
//fileName = DateTime.Now.ToString("hh:mm:ss");
} lock (logLock)
{
File.AppendAllLines(basePath + "\\Log\\" + dataString + "\\" + fileName, logText);
}
}
catch (Exception) { }
} /// <summary>
/// Write exception to log file
/// </summary>
/// <param name="exception">Exception</param>
public void WriteException(Exception exception, string specialText = null)
{
if (exception != null)
{
Type exceptionType = exception.GetType();
string text = string.Empty;
if (!string.IsNullOrEmpty(specialText))
{
text = text + specialText + Environment.NewLine;
}
text = "Exception: " + exceptionType.Name + Environment.NewLine;
text += " " + "Message: " + exception.Message + Environment.NewLine;
text += " " + "Source: " + exception.Source + Environment.NewLine;
text += " " + "StackTrace: " + exception.StackTrace + Environment.NewLine;
WriteLog(text, LogType.Error);
}
} }
}
上一篇:这么设计,Redis 10亿数据量只需要100MB内存


下一篇:Mysql大数据量查询优化