一个简单的写txt格式Log的方法,支持多线程

using System;
using System.IO;
using System.Web;

public class SimpleLog
{
    #region 写日志,指定文件夹、文件名称、内容
    public static void Write(string logPath, string fileName, string content)
    {
        try
        {
            // 常用的获取服务器目录的方法,但在多线程环境下,会调用失败;
            // string strPath = HttpContext.Current.Server.MapPath(logPah);

            string folderPath = HttpRuntime.AppDomainAppPath + "/log";

            if (logPath.Trim() != "")
            {
                folderPath += "/" + logPath;
            }

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            folderPath = folderPath + "\\" + fileName + ".txt";

            StreamWriter fs = new StreamWriter(folderPath, true, System.Text.Encoding.UTF8);
            fs.WriteLine(content);
            fs.Close();
        }
        catch(Exception ex)
        { }
    }
    #endregion

    #region 在LOG文件夹根目录下写日志
    public static void Write(string content)
    {
        content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss    ") + content;
        string fileName = DateTime.Today.ToString("yyyyMMdd");
        Write("", fileName, content);
    }
    #endregion

    #region 在特定文件夹写日志
    public static void Write(string folderName, string content)
    {
        string fileName = DateTime.Today.ToString("yyyyMMdd");
        content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss    ") + content;
        Write(folderName, fileName, content);
    }
    #endregion
}


只包含写的方法,用来记录一些简单的内容,更高级的建议还是使用Log4Net这类专业的工具。

调用方法很简单:

SimpleLog.Write("xxx", “要记录的内容”);
或者用异步的方式:

var task = new TaskFactory().StartNew(() =>
            {
                SimpleLog.Write("xxx", "要记录的内容");
            });

会在站点根目录的/log/xxx目录下生成以当前日期命名的文件,如20161005.txt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值