自己写的Log日志记录类,支持文件和数据库,自动建立Log表格

自己写的 Log日志记录类,支持文件和数据库,自动建立Log表格,刚学设计模式,大家别见笑。

文件:ILog.cs代码

using  System;

namespace  LZ2007.Function.Log
... {
    
/**//// <summary>
    
/// 日志通用接口
    
/// </summary>

    public interface ILog
    
...{
        
void Info(string message, int level);
        
void Info(string message);
        
void Warn(string message, int leave);
        
void Warn(string message);
        
void Debug(string message, int leave);
        
void Debug(string message);
        
void Error(string message, Exception e, int leave);
        
void Error(string message, Exception e);
        
void Fatal(string message, Exception e, int leave);
        
void Fatal(string message, Exception e);
        
void Close();
    }

}

文件LogManage.cs代码

using  System;
using  System.Data;
using  System.Configuration;

namespace  LZ2007.Function.Log
... {
    
/**//// <summary>
    
/// 日志工厂类
    
/// </summary>

    public static class LogFactory
    
...{
        
public static ILog GetLog(Type objType)
        
...{
            
int _LogType = Convert.ToInt32(ConfigurationManager.AppSettings["eLogType"]);
            ILog log 
= null;
            
if (_LogType == 1)
            
...{
                log 
= new DataBaseLog(objType);
            }

            
else if(_LogType==0)
            
...{
                log 
= new FileLog(objType);
            }

            
return log;
        }

    }

}
文件DataBaseLog.cs代码
using  System;
using  System.Data;
using  System.Configuration;
using  System.Web;

using  System.Data.SqlClient;

namespace  LZ2007.Function.Log
... {
    
/**//// <summary>
    
/// 数据库日志类.
    
/// </summary>

    public class DataBaseLog : ILog
    
...{
        
私有变量申明#region 私有变量申明
        
private string _LogConnStr;
        
private string _LogObjectSource;

        
private bool _isDebug;
        
private bool _isInfo;
        
private bool _isError;
        
private bool _isWarn;

        
private SqlConnection _sqlConn;

        
public bool IsDebug
        
...{
            
get ...return _isDebug; }
            
set ...{ _isDebug = value; }
        }

        
public bool IsInfo
        
...{
            
get ...return _isInfo; }
            
set ...{ _isInfo = value; }
        }

        
public bool IsError
        
...{
            
get ...return _isError; }
            
set ...{ _isError = value; }
        }

        
public bool IsWarn
        
...{
            
get ...return _isWarn; }
            
set ...{ _isWarn = value; }
        }

        
#endregion


        
public DataBaseLog(Type objType)
        
...{
            _isDebug 
= Convert.ToBoolean(ConfigurationManager.AppSettings["eLogDebug"]);
            _isInfo 
= Convert.ToBoolean(ConfigurationManager.AppSettings["eLogInfo"]);
            _isError 
= Convert.ToBoolean(ConfigurationManager.AppSettings["eLogError"]);
            _isWarn 
= Convert.ToBoolean(ConfigurationManager.AppSettings["eLogWarn"]);
            _LogObjectSource 
= objType.FullName;
            
//_LogType = Convert.ToInt32(ConfigurationManager.AppSettings["eLogType"]);
            _LogConnStr = ConfigurationManager.AppSettings["eLogConnStr"];
            _sqlConn 
= new SqlConnection(_LogConnStr);
            Init();
        }


        
private void Init()
        
...{
            
//检查是否有该表
            string strTest = "select count(name)as a1 from sysobjects where id = object_id(N’[LOGSYSTEM]’) and OBJECTPROPERTY(id, N’IsUserTable’) = 1";

            
//建立表
            string strSQL = "CREATE TABLE [dbo].[LOGSYSTEM] (" +
                                
"[lId] [int] IDENTITY (1, 1) NOT NULL ," +
                                
"[lMessage] [nvarchar] (1000) COLLATE Chinese_PRC_CI_AS NULL ," +
                                
"[lLevel] [int] NULL ," +
                                
"[lSource] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ," +
                                
"[lException] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ," +
                                
"[lType] [int] NULL ," +
                                
"[lDate] [datetime] NULL ," +
                                
"[lADDIT1] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ," +
                                
"[lADDIT2] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ," +
                                
"[lADDIT3] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL " +
                            
") ON [PRIMARY]";

            _sqlConn.Open();
            SqlCommand sqlcomm 
= new SqlCommand(strTest, _sqlConn);
            
int i = (int)sqlcomm.ExecuteScalar(); ;
            
if (i == 0)
            
...{
                sqlcomm 
= new SqlCommand(strSQL, _sqlConn);


                sqlcomm.ExecuteNonQuery();
            }

            sqlcomm.Dispose();
        }


        
private int insertLog(string message, int level, string source, string exception, int type)
        
...{

            
string strSQL = "INSERT INTO LOGSYSTEM(lMessage,lLevel,lSource,lException,lType,lDate) " +
                
"VALUES (@lMessage,@lLevel,@lSource,@lException,@lType,@lDate)";
            SqlCommand sqlcomm 
= new SqlCommand(strSQL, _sqlConn);
            
if (_sqlConn.State == ConnectionState.Closed)
            
...{
                _sqlConn.Open();
            }

            sqlcomm.Parameters.Add(
"@lMessage", SqlDbType.NVarChar, 1000);
            sqlcomm.Parameters[
"@lMessage"].Direction = ParameterDirection.Input;
            sqlcomm.Parameters[
"@lMessage"].Value = message;

            sqlcomm.Parameters.Add(
"@lLevel", SqlDbType.Int);
            sqlcomm.Parameters[
"@lLevel"].Direction = ParameterDirection.Input;
            sqlcomm.Parameters[
"@lLevel"].Value = level;

            sqlcomm.Parameters.Add(
"@lSource", SqlDbType.NVarChar, 100);
            sqlcomm.Parameters[
"@lSource"].Direction = ParameterDirection.Input;
            sqlcomm.Parameters[
"@lSource"].Value = source;

            sqlcomm.Parameters.Add(
"@lException", SqlDbType.NVarChar, 100);
            sqlcomm.Parameters[
"@lException"].Direction = ParameterDirection.Input;
            sqlcomm.Parameters[
"@lException"].Value = exception;

            sqlcomm.Parameters.Add(
"@lType", SqlDbType.Int);
            sqlcomm.Parameters[
"@lType"].Direction = ParameterDirection.Input;
            sqlcomm.Parameters[
"@lType"].Value = type;

            sqlcomm.Parameters.Add(
"@lDate", SqlDbType.DateTime);
            sqlcomm.Parameters[
"@lDate"].Direction = ParameterDirection.Input;
            sqlcomm.Parameters[
"@lDate"].Value = DateTime.Now;
            
return sqlcomm.ExecuteNonQuery();
        }


        
public void Close()
        
...{
            
this.Info("Log End"5);
            _sqlConn.Close();
        }


        
信息[Info]#region 信息[Info]
        
public void Info(string message, int level)
        
...{
            
if (_isInfo)
            
...{
                insertLog(message, level, _LogObjectSource, 
""0);
            }

        }


        
public void Info(string message)
        
...{
            
if (_isInfo)
            
...{
                insertLog(message, 
0, _LogObjectSource, ""0);
            }

        }

        
#endregion


        
警告[Warn]#region 警告[Warn]
        
public void Warn(string message)
        
...{
            
if (_isWarn)
            
...{
                insertLog(message, 
0, _LogObjectSource, ""1);
            }

        }


        
public void Warn(string message, int leave)
        
...{
            
if (_isWarn)
            
...{
                insertLog(message, leave, _LogObjectSource, 
""1);
            }

        }

        
#endregion


        
调试[Debug]#region 调试[Debug]
        
public void Debug(string message, int leave)
        
...{
            
if (_isDebug)
            
...{
                insertLog(message, leave, _LogObjectSource, 
""2);
            }

        }


        
public void Debug(string message)
        
...{
            
if (_isDebug)
            
...{
                insertLog(message, 
0, _LogObjectSource, ""2);
            }

        }

        
#endregion


        
错误[Error]#region 错误[Error]
        
public void Error(string message, Exception e, int leave)
        
...{
            
if (_isError)
            
...{
                
if (e != null)
                
...{
                    insertLog(message, leave, _LogObjectSource, e.Message, 
3);
                }

                
else
                
...{
                    insertLog(message, leave, _LogObjectSource, 
""3);
                }

            }

        }


        
public void Error(string message, Exception e)
        
...{
            
if (_isError)
            
...{
                
if (e != null)
                
...{
                    insertLog(message, 
0, _LogObjectSource, e.Message, 3);
                }

                
else
                
...{
                    insertLog(message, 
0, _LogObjectSource, ""3);
                }

            }

        }

        
#endregion


        
致命错误[Fatal]#region 致命错误[Fatal]
        
public void Fatal(string message, Exception e, int leave)
        
...{
            
if (e != null)
            
...{
                insertLog(message, leave, _LogObjectSource, e.Message, 
4);
            }

            
else
            
...{
                insertLog(message, leave, _LogObjectSource, 
""4);
            }

        }


        
public void Fatal(string message, Exception e)
        
...{
            
if (e != null)
            
...{
                insertLog(message, 
0, _LogObjectSource, e.Message, 4);
            }

            
else
            
...{
                insertLog(message, 
0, _LogObjectSource, ""4);
            }

        }

        
#endregion


    }

}

文件FileLog.cs代码

using  System;
using  System.Data;
using  System.Configuration;
using  System.Web;

using  System.IO;

namespace  LZ2007.Function.Log
... {
    
/**//// <summary>
    
/// FileLog 的摘要说明
    
/// </summary>
    
/// 

    public class FileLog : ILog
    
...{
        
私有变量申明#region 私有变量申明
        
private string _LogFile;
        
private string _LogMsgFormat;
        
private string _LogObjectSource;

        
private StreamWriter sw;
        
private bool _isDebug;
        
private bool _isInfo;
        
private bool _isError;
        
private bool _isWarn;

        
public bool IsDebug
        
...{
            
get ...return _isDebug; }
            
set ...{ _isDebug = value; }
        }

        
public bool IsInfo
        
...{
            
get ...return _isInfo; }
            
set ...{ _isInfo = value; }
        }

        
public bool IsError
        
...{
            
get ...return _isError; }
            
set ...{ _isError = value; }
        }

        
public bool IsWarn
        
...{
            
get ...return _isWarn; }
            
set ...{ _isWarn = value; }
        }

        
#endregion


        
public FileLog(Type objType)
        
...{
            _isDebug 
= Convert.ToBoolean(ConfigurationManager.AppSettings["eLogDebug"]);
            _isInfo 
= Convert.ToBoolean(ConfigurationManager.AppSettings["eLogInfo"]);
            _isError 
= Convert.ToBoolean(ConfigurationManager.AppSettings["eLogError"]);
            _isWarn 
= Convert.ToBoolean(ConfigurationManager.AppSettings["eLogWarn"]);
            _LogObjectSource 
= objType.FullName;
            _LogFile 
= ConfigurationManager.AppSettings["eLogFile"];
            _LogMsgFormat 
= ConfigurationManager.AppSettings["eLogMsgFormat"];
            Init();
        }


        
public void Close()
        
...{
            
this.Info("Log End"5);
            sw.Close();
        }


        
私有函数实现#region 私有函数实现
        
private void Init()
        
...{
            
string path = HttpContext.Current.Server.MapPath("~/"+ _LogFile;
            sw 
= File.AppendText(path);
        }


        
private void insertLog(string message, int level, string source, string exception, int type)
        
...{
            
string sType = string.Empty;
            
string msg = _LogMsgFormat;
            msg 
= msg.Replace("{$message}", message);
            msg 
= msg.Replace("{$level}", level.ToString());
            msg 
= msg.Replace("{$source}", source);
            msg 
= msg.Replace("{$exception}", exception);

            
switch (type)
            
...{
                
case 0:
                    
...{
                        sType 
= "Info";
                        
break;
                    }

                
case 1:
                    
...{
                        sType 
= "Warn";
                        
break;
                    }

                
case 2:
                    
...{
                        sType 
= "Debug";
                        
break;
                    }

                
case 3:
                    
...{
                        sType 
= "Error";
                        
break;
                    }

                
case 4:
                    
...{
                        sType 
= "Fatal";
                        
break;
                    }

            }

            msg 
= msg.Replace("{$type}", sType);
            msg 
= msg.Replace("{$time}", DateTime.Now.ToString());
            sw.WriteLine(msg);
            sw.Flush();
        }

        
#endregion


        
信息[Info]#region 信息[Info]
        
public void Info(string message, int level)
        
...{
            
if (_isInfo)
            
...{
                insertLog(message, level, _LogObjectSource, 
""0);
            }

        }


        
public void Info(string message)
        
...{
            
if (_isInfo)
            
...{
                insertLog(message, 
0, _LogObjectSource, ""0);
            }

        }

        
#endregion


        
警告[Warn]#region 警告[Warn]
        
public void Warn(string message)
        
...{
            
if (_isWarn)
            
...{
                insertLog(message, 
0, _LogObjectSource, ""1);
            }

        }


        
public void Warn(string message, int leave)
        
...{
            
if (_isWarn)
            
...{
                insertLog(message, leave, _LogObjectSource, 
""1);
            }

        }

        
#endregion


        
调试[Debug]#region 调试[Debug]
        
public void Debug(string message, int leave)
        
...{
            
if (_isDebug)
            
...{
                insertLog(message, leave, _LogObjectSource, 
""2);
            }

        }


        
public void Debug(string message)
        
...{
            
if (_isDebug)
            
...{
                insertLog(message, 
0, _LogObjectSource, ""2);
            }

        }

        
#endregion


        
错误[Error]#region 错误[Error]
        
public void Error(string message, Exception e, int leave)
        
...{
            
if (_isError)
            
...{
                
if (e != null)
                
...{
                    insertLog(message, leave, _LogObjectSource, e.Message, 
3);
                }

                
else
                
...{
                    insertLog(message, leave, _LogObjectSource, 
""3);
                }

            }

        }


        
public void Error(string message, Exception e)
        
...{
            
if (_isError)
            
...{
                
if (e != null)
                
...{
                    insertLog(message, 
0, _LogObjectSource, e.Message, 3);
                }

                
else
                
...{
                    insertLog(message, 
0, _LogObjectSource, ""3);
                }

            }

        }

        
#endregion


        
致命错误[Fatal]#region 致命错误[Fatal]
        
public void Fatal(string message, Exception e, int leave)
        
...{
            
if (e != null)
            
...{
                insertLog(message, leave, _LogObjectSource, e.Message, 
4);
            }

            
else
            
...{
                insertLog(message, leave, _LogObjectSource, 
""4);
            }

        }


        
public void Fatal(string message, Exception e)
        
...{
            
if (e != null)
            
...{
                insertLog(message, 
0, _LogObjectSource, e.Message, 4);
            }

            
else
            
...{
                insertLog(message, 
0, _LogObjectSource, ""4);
            }

        }

        
#endregion

    }

}

配置文件Web.config

 

  < appSettings >
    
< add  key ="eLogConnStr"  value ="Data Source=LZSHSQLSERVER2005;Initial Catalog=LZDB;Persist Security Info=True;User ID=sa;password=oilchem2007;"   />
    
< add  key ="eLogFile"  value ="sys.log"   />
    
< add  key ="eLogType"  value ="1"   />
    
< add  key ="eLogDebug"  value ="False"   />
    
< add  key ="eLogInfo"  value ="True"   />
    
< add  key ="eLogError"  value ="True"   />
    
< add  key ="eLogWarn"  value ="True"   />
    
< add  key ="eLogMsgFormat"  value ="{$type}[{$time}]:{$message}:({$level})  --- {$source}[{$exception}]" />
  
</ appSettings >

测试代码:

 

     private   static  ILog log  =  LogFactory.GetLog( typeof (Test));
    
protected   void  Page_Load( object  sender, EventArgs e)
    
... {
        
int i = 10, j = 0, k;
        
try
        
...{
            log.Info(
"记录一下信息!");
            k 
= i / j;
        }

        
catch (Exception e1)
        
...{
            log.Error(
"发生错误1", e1);
        }

        
finally
        
...{
            log.Close();
        }

    }

最后附上全部代码:
/Files/eicesoft/Log.zip

转载于:https://www.cnblogs.com/eicesoft/archive/2007/09/12/839164.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值