最近小编在研究一些功能,有些代码小编需要查看详细的信息,思来想去还是觉得搞个日志比较好,就在网上查看了一些博客并将其改成自己想要的样子,下面是小编借鉴其他博客并优化了的一些代码,对小编研究小功能提供了不少的帮助哦!
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
namespace Verification
{
public class WriteLog
{
private static StreamWriter streamWriter; //写文件
public static void WriteError(int type, string message)
{
try
{
//DateTime dt = new DateTime();
string directPath = ConfigurationManager.AppSettings["LogFilePath"].ToString().Trim(); //在获得文件夹路径
if (!Directory.Exists(directPath)) //判断文件夹是否存在,如果不存在则创建
{
Directory.CreateDirectory(directPath);
}
directPath += string.Format(@"\{0}.log", DateTime.Now.ToString("yyyy-MM-dd"));
if (streamWriter == null)
{
streamWriter = !File.Exists(directPath) ? File.CreateText(directPath) : File.AppendText(directPath); //判断文件是否存在如果不存在则创建,如果存在则添加。
}
streamWriter.WriteLine("***********************************************************************");
streamWriter.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
//streamWriter.WriteLine("输出信息:错误信息");
if (message != null)
{
if (type == 0)
{
streamWriter.WriteLine("记录信息:\r\n" + message);
}
else {
streamWriter.WriteLine("异常信息:\r\n" + message);
}
}
}
finally
{
if (streamWriter != null)
{
streamWriter.Flush();
streamWriter.Dispose();
streamWriter = null;
}
}
}
}
}
配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<!-- 系统日志保存路径-->
<add key="LogFilePath" value="D://ErrorLog" />
</appSettings>
</configuration>
调用
static void Main(string[] args)
{
try
{
var i = 0;
var j = 1 / i;
WriteLog.WriteError(0,j.ToString());
}
catch (Exception ex)
{
WriteLog.WriteError(1,ex.ToString());
throw;
}
}
参考相关博客
c# 日志操作类 (将日志记录在txt文本里)
女同事脸有点大,今天问我:你说,我颜值高不高?
我:相当的高!
赞得她乐呵呵的,又问:拍马屁的吧,那你说的具体点?
我:这还有假,按你脸的面积求解可得。。。
哎玛,追着我打。。