工具没有好坏,只有适不适用。由于项目中用 Log4Net 过重,所以使用 Trace 代替了 Log4Net 输入一些简单的日志信息;

自定义监听文件

using System;
using System.Configuration;
using System.Diagnostics;
using System.IO; namespace Iron.Common
{
/// <summary>
/// 错误日志自定义监听
/// </summary>
public class LogHelper : TraceListener
{
/// <summary>
/// 获取日志输出级别
/// </summary>
public static TraceSwitch TraceSwitch = new TraceSwitch("TraceLevel", string.Empty); public LogHelper()
{
if (TraceSwitch.Level == TraceLevel.Off)
{
TraceSwitch.Level = TraceLevel.Error;
}
} /// <summary>
/// 如果AppConfig 里面有配置就读配置文件里面的路径,否则取当前exe目录
/// </summary>
private string FilePath
{
get
{
string directPath = ConfigurationManager.AppSettings["LogFilePath"]; //获得文件夹路径
if (string.IsNullOrEmpty(directPath))
{
directPath = System.Environment.CurrentDirectory + @"\logs\";
}
directPath = directPath.Trim();
if (!Directory.Exists(directPath)) //判断文件夹是否存在,如果不存在则创建
{
Directory.CreateDirectory(directPath);
}
return string.Format(@"{0}\{1}_{2}.log", directPath, DateTime.Now.ToString("yyyy.MM.dd"), System.Diagnostics.Process.GetCurrentProcess().ProcessName);
}
} public override void Write(string message)
{
File.AppendAllText(FilePath, message);
} public override void WriteLine(string message)
{
File.AppendAllText(FilePath, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + message + Environment.NewLine);
} public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
if ((int)TraceSwitch.Level + >= (int)eventType)
base.TraceEvent(eventCache, source, eventType, id, message);
} public override void Write(object o, string category)
{
string msg = ""; if (string.IsNullOrEmpty(category) == false) //category参数不为空
{
msg = category + " : ";
} if (o is Exception) //如果参数o是异常类,输出异常消息+堆栈,否则输出o.ToString()
{
var ex = (Exception)o;
msg += ex.Message + Environment.NewLine;
msg += ex.StackTrace;
}
else if (o != null)
{
msg = o.ToString();
} WriteLine(msg);
}
}
}

测试代码

private static void Main(string[] args)
{
//删除初始化代码,改为在配置文件中设置--【此代码只要在程序运行时初始化一次】
Trace.Listeners.Clear(); //清除系统监听器 (就是输出到Console的那个)
Trace.Listeners.Add(new LogHelper()); //添加 自定义Trace 实例 try
{
int a = ;
int b = ;
var sd = a / b;
}
catch (Exception ex)
{
Trace.TraceError("{0}\r\n{1}", ex.Message, ex.StackTrace);
}
return;
}

输出日志为:

ODAS.exe Error:  : -- ::    Attempted to divide by zero.
at Ironfo.Test.Views.Demo01.List.ControlRefresh(Object sender, RoutedEventArgs routedEventArgs) in C:\Code\ODAS\Views\Demo01\List.xaml.cs:line

如果要修改日志的级别、修改日志输出目录,可修改配置文件:

<configuration>
<!-- 默认输入为 Error 【默认为Off,已在代码中修改为Error】 -->
<system.diagnostics>
<switches>
<!--这里可以设定监听级别,可以设置Error,Warning,Info,Verbose或者留空-->
<add name="TraceLevel" value="Info"/>
</switches>
</system.diagnostics>
<appSettings>
<!-- 默认为执行文件所在的目录 -->
<!--<add key="LogFilePath" value="D:\LOG" />-->
</appSettings>
</configuration>

注意:Trace.Write() 等日志输出方法,不受等级的限制

使用 Trace 将日志输入到文件中的更多相关文章

  1. 使用exec函数将当前的信息输入到文件中

    先来看看exec函数: exec函数族     fork创建子进程后执行的是和父进程相同的程序(但有可能执行不同的代码分支),子进程往往要调用一种exec函数以执行另一个程序.当进程调用一种exec函 ...

  2. C#写入日志信息到文件中

    为了在服务器上运行程序及时的跟踪出错的地方,可以在必要的地方加入写日志的程序. string folder = string.Format(@"D:\\{0}\\{1}", Dat ...

  3. Log4j分级别保存日志到单个文件中,并记录IP和用户信息

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration S ...

  4. php把错误日志输入到文件里。

    display_errors = On 开启状态下,若出现错误,则报错,出现错误提示 dispaly_errors = Off 关闭状态下,若出现错误,则提示:服务器错误.但是不会出现错误提示 log ...

  5. log4j+AOP 记录错误日志信息到文件中

    AOP 采用异常通知切入,把指定包的异常记录到日志文件. 先看log4j.properties ,控制台输出的是普通信息, 文件输出的是异常信息. log4j.rootLogger=DEBUG, Co ...

  6. python logging日志输出个文件中

    # -*- coding:utf-8 -*- import logging # 引入logging模块 import os.path import time # 第一步,创建一个logger logg ...

  7. linux下将终端的输入存入文件中

    代码很简单: #include <stdlib.h> #include <fcntl.h> #include <stdio.h> #include <unis ...

  8. 把Android studio的日志导入目标文件中

    最好是在Android studio的命令行工具中进行命令操作. adb logcat -v time > /Users/z/log.txt adb logcat -v time > /U ...

  9. ios 将Log日志重定向输出到文件中保存

    对于真机,日志没法保存,不好分析问题.所以有必要将日志保存到应用的Docunment目录下,并设置成共享文件,这样才能取出分析. 首先是日志输出,分为c的printf和标准的NSLog输出,print ...

随机推荐

  1. block(四)揭开神秘面纱(下)-b

    看此篇时,请大家同时打开两个网址(或者下载它们到本地然后打开): http://llvm.org/svn/llvm-project/compiler-rt/trunk/lib/BlocksRuntim ...

  2. elasticsearch实现按天翻滚索引

    最近在做集中式日志,将应用的日志保存到Elasticsearch中,结合kibana实现集中化日志监控和报警.在设计ES存储的时候.考虑到日志的特殊性,打算采用Daily Indices方式.名称为: ...

  3. MySQL-慢查询日志

    慢查询日志功能默认不开启,其记录了执行时间超过参数long_query_time的值(默认是10),且访问的行数超过了参数min_examined_row_limit的值得SQL语句. mysql&g ...

  4. SharePoint 2013 Farm 安装指南——构建一个双层SharePoint Farm

    最近要对公司里的SharePoint进行升级,由于旧的系统SharePoint 2010已经有2年了,上面改动比较多,而且权限也很混乱了,所以下定决心要对其做一次升级,重新部署一台新的SharePoi ...

  5. SAML

    From the book <Modern Authentication with Azure Active Directory for Web Applications> SAML Th ...

  6. jQuery的prop和attr的区别,及判断复选框是否选中

    jQuery的prop和attr的区别 对于HTML元素本身就带有的固有属性,在处理时,使用prop方法. 对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法. 参数有区别,att ...

  7. List遍历Java 8 Streams map() examples

    1. A List of Strings to Uppercase 1.1 Simple Java example to convert a list of Strings to upper case ...

  8. 【转】WARNING! File system needs to be upgraded. You have version null and I want version 7. Run the '${HBASE_HOME}/bin/hbase migrate' script. 的解决办法

    前段时间集群出问题,hadoop和hbase启动不了了. 后来hadoop回复了,hbase死活master无法启动.打开日志发现报了以下错误: WARNING! File system needs ...

  9. p标签不折行的问题

    问题描述: 一个固定宽度的div里面包了一个p元素,由于p元素中的文字比较长并且没有换行,最终看到的效果就是p中的 文字“跑”了出来. 问题复现: <div style="width: ...

  10. 【R】R语言常用函数

    R语言常用函数 基本 一.数据管理vector:向量 numeric:数值型向量 logical:逻辑型向量character:字符型向量 list:列表 data.frame:数据框c:连接为向量或 ...