0
点赞
收藏
分享

微信扫一扫

log4net 不打印日志,无log文件,无日志文件,程序运行正常不报错

问题: 调用log4net写日志;程序正常运行无报错,但是发现没有log日志 

尝试方案:[assembly: log4net.Config.XmlConfigurator(Watch = true)]   (无效)

分析思路

一、确保你已经引用log4net.dll

 

二、确保你项目的bin目录下有log4net.dll以及log4.xml文件

 

三、确定项目存在log4net.config的配置文件

 

四、log4net.config配置文件的路径是否正确,并且程序在获取log4net.config的配置文件路径是否正确

 

我的代码

FileInfo configFile = new FileInfo(HttpContext.Current.Server.MapPath("/Configs/log4net.config"));
log4net.Config.XmlConfigurator.Configure(configFile);//加载配置文件
log = log4net.LogManager.GetLogger(typeof(Log));//通过反射获取日志对象实例

我项目保证前三项检查无误,就是处在获取配置文件的时候出错了 ,因为我的是控制台项目

如果你的项目是控制台或者winform项目请继续往下看

 控制台项目winform项目的根目录就在“\bin\Debug\”下面

 

五、你的项目是否是控制台程序

你应该把log4net.config的配置文件放到“\bin\Debug\”下面,你的输入日志也在“\bin\Debug\”下面;

因为控制台项目winform项目的根目录就在“\bin\Debug\”下面

 

log4net 不打印日志,无log文件,无日志文件,程序运行正常不报错_xml

如果你的项目类型不是 “Debug”是“Release” ,就在“\bin\Release\”下面

如果你有强迫症,就需要修改你的代码

FileInfo configFile = new FileInfo(MapPath("Configs/log4net.config"));
log4net.Config.XmlConfigurator.Configure(configFile);//加载配置文件
log = log4net.LogManager.GetLogger(typeof(Log));//通过反射获取日志对象实例
/// <summary>
/// 获取文件路径
/// </summary>
/// <param name="strPath"></param>
/// <returns></returns>
private static string MapPath(string strPath)
{
if (HttpContext.Current != null)
{
return HttpContext.Current.Server.MapPath(strPath);
}
else //非web程序引用
{
strPath = strPath.Replace("/", "\\");
if (strPath.StartsWith("\\"))
{
strPath = strPath.TrimStart('\\');
}

string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string _path = "";

#region 过滤 bin和Debug目录
{
string[] str = baseDirectory.Split('\\');

foreach (var item in str)
{
Console.WriteLine(item);
if (item.ToString() != "bin" && item.ToString() != "Debug")
{
_path += $"{item}\\";
}
}
_path = _path.Remove(_path.Length - 1, 1);
}
#endregion

return System.IO.Path.Combine(_path, strPath);
}
}

 这仅仅是修改了读取log4net.config配置文件方法,

如果你还想修改输出日志的路径;

解决1:就把配置文件里生成日志的路径改成“绝对路径”(全路径)

解决2:读这篇文章

六、你的项目是否是winForm项目

请看第三项

以上六项都没有检查到问题

 

七、一定是你log4net.config配置文件里的生成文件路径存在问题

打开log4net.config配置文件文件

找到节点

<file value="File/log/logContent.txt" />

<param name="File" value="D:\NFine_log"/>

(第一点段代码是相对路径,第二段代码是绝对路径)

如果你的是相对路径,切记路径前面不能带“/”直接文件夹的名称就行了

如果你写成<file value="/File/log/logContent.txt" />日志写入就错误了

 

 

 


举报

相关推荐

0 条评论