4)日志操作

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace SyLib
{
    /// <summary>
    /// 日志操作
    /// </summary>
    public class log
    {
        /// <summary>
        /// 错误信息类
        /// </summary>
        /// <param name="errorClass">发生错误的类</param>
        /// <param name="errorFunction">发生错误的方法</param>
        /// <param name="errorContent">错误内容</param>
        /// <returns></returns>
        public static bool WriteErrorLog(string errorClass, string errorFunction, string errorContent)
        {
            string path = System.Web.HttpContext.Current.Server.MapPath("~");
            bool isOK = false;
            string errorFilePath = path + "/error/"+DateTime.Now.ToString("yyyy-MM-dd")+".txt";
            StreamWriter sw = new StreamWriter(errorFilePath, true);
            try
            {
                string errorCode = Guid.NewGuid().ToString();
                sw.WriteLine(errorCode);
                sw.WriteLine("发生时间:" + DateTime.Now);
                sw.WriteLine("错误发生类或文件:" + errorClass);
                sw.WriteLine("错误发生方法:" + errorFunction);
                sw.WriteLine("错误内容:" + errorContent);
                sw.WriteLine("----------------------------------------------------------------");
                sw.Close();
                System.Web.HttpContext.Current.Response.Write("发生错误!错误代号:" + errorCode);
                isOK = true;
            }
            catch
            {
                sw.Close();
                System.Web.HttpContext.Current.Response.Write("写错误日志时发生错误!");
            }
            return isOK;
        }

        #region 写文件 利用StreamWriter 处理字符串
        /// <summary>
        /// 写文件 利用StreamWriter 处理字符串
        /// </summary>
        /// <param name="filePath">文件路径(包括文件名)</param>
        /// <param name="content">内容</param>
        /// <param name="codeType">编码格式 如: utf-8, gb2312</param>
        /// <returns></returns>
        public static bool WriteFile(string filePath, string content, string codeType)
        {
            bool returnValue = false;
            Encoding coding = System.Text.Encoding.Default;
            if (codeType != null)
            {
                coding = System.Text.Encoding.GetEncoding(codeType);
            }

            filePath = SyFile.GetMapPath(filePath);
            if (filePath != null)
            {
                StreamWriter sw = new StreamWriter(filePath, true/*true代表追加 false代表重写*/, coding);
                try
                {
                    sw.Write(content);
                    sw.Flush();
                    returnValue = true;
                }
                catch
                {
                    throw;
                }
                finally
                {
                    sw.Close();
                    sw.Dispose();
                }

            }

            return returnValue;
        }
        #endregion

    }
}

posted @ 2010-02-22 16:43  不帅你砍我  阅读(123)  评论(0)    收藏  举报