用文本简单的记录日志

前天,小皇帝教了一个日志功能,之前编程从来都没有想过这个问题,那就是如果程序部署到服务器之后出现错误怎么办?写一个日志跟踪就解决了大家的问题了。

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

namespace CoreProxy
{
    
public  class LogService
    {
        
private  bool m_isWriteLog = true;  //是否写日志

        
private  String m_logFilePath = String.Empty;  //日志路径

        
private  String m_time;  //时间字符串

        
public  void InitLog(String layerIndex, String logPath)
        {
            
//日志写入路径
            if (!String.IsNullOrEmpty(logPath))
            {
                
//赋值时间字串
                m_time = GetTimeStr();
                
if (!String.IsNullOrEmpty(logPath))
                {
                    
//路径不存在则创建一个
                    if (!Directory.Exists(logPath))
                    {
                        Directory.CreateDirectory(logPath);
                    }
                    
//名字用实时的还是历史的
                    String logName = "_log_";

                    
//这样组成一个文件路径
                    String filePath = logPath + "\\" + layerIndex + logName + m_time + ".txt";
                    
//付给文件路径的地址
                    m_logFilePath = filePath;
                    
                }
            }
        }

        
public  void WriteLog(String msg)
        {
            
try
            {
                
lock (this)
                {
                    
if (m_isWriteLog)
                    {
                        
if (!File.Exists(m_logFilePath))
                        {
                            
using (FileStream fs = File.Create(m_logFilePath))
                            {
                                fs.Close();
                                fs.Dispose();
                            }
                        }
                        
using (StreamWriter sw = File.AppendText(m_logFilePath))
                        {
                            sw.WriteLine(msg);
                            sw.Flush();
                            sw.Close();
                        }
                    }
                }
            }
            
catch { }
        }
        
public  String GetTimeStr()
        {
            
return DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day;
        }

    }
}

下面带有一个简单的源代码/Files/SissyNong/Upload.rar

 

posted @ 2009-09-21 19:23  Sissynong  阅读(311)  评论(0编辑  收藏  举报