NLog for Linq2Sql
linq自动产生的sql命令, 可能会是没有效率的, 故需要log 出来, 再进行调整.
应用 DataContext的属性Log:System.IO.TextWriter 再加上NLog
合成一个好用的 class
using System.IO;
using NLog;
using System.ComponentModel;
using System.Text;
namespace Common.NMail.Core {
/// /// 包装NLog.Logger对象为TextWriter类型 /// 以利LinqToSql的Log用. ///
public class NLogTextWriter : TextWriter {
/// /// 日志对象 /// proxy pattern::有需要时再建立 ///
private Logger _logger = null;
/// /// 日志层级::默认为Info ///
///
private LogLevel _level = NLog.LogLevel.Info;
/// /// 默认建构子, 自动产生日志对象 ///
public NLogTextWriter() {
}
/// /// 默认建构子, 自动产生日志对象, 并修改默认的日志层级 ///
public NLogTextWriter(NLog.LogLevel level) {
if (level != null) {
_level = level;
}
}
/// /// 使用已建立的日志对象 ///
///
public NLogTextWriter(NLog.Logger logger) {
_logger = logger;
}
/// /// 使用已建立的日志对象, 并修改默认的日志层级 ///
///
///
public NLogTextWriter(NLog.Logger logger,NLog.LogLevel level) {
_logger = logger;
_level = level;
}
///
public override void Write(char[] buffer) {
string value = new string(buffer);
Write(value);
}
///
public override void Write(char[] buffer, int index, int count) {
Write(new string(buffer, index, count));
}
///
public override void WriteLine(char[] buffer) {
Write(new StringBuilder(new string(buffer)).Append("rn").ToString());
}
///
public override void WriteLine(char[] buffer, int index, int count) {
Write(new StringBuilder(new string(buffer, index, count)).Append("rn").ToString());
}
///
public override void WriteLine(string value) {
Write(new StringBuilder(value).Append("rn").ToString());
}
///
public override void Write(string value) {
if(_logger==null){
_logger = LogManager.GetCurrentClassLogger();
}
_logger.Log(_level, value);
}
/// /// (只读)系统输出文字的编码方式 ///
public override System.Text.Encoding Encoding {
get {
return System.Text.Encoding.Default;
}
}
}
}