我正在尝试使用Log4Net登录到ASP.Net站点中的文件,但我的实现只是不创建文件。我看了一千遍代码并将它与我发现的一些解决方案进行了比较,但未能弄清楚错误,所以也许你们可以帮助我。 我们走了:
我的Web.Config看起来像这样:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.serviceModel">
<section name="domainServices" type="System.ServiceModel.DomainServices.Hosting.DomainServicesSection, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication" requirePermission="false" />
</sectionGroup>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<root>
<level value="ALL"/>
<appender name="RollingFileAppender"/>
</root>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender, log4net">
<file value="mylogfile.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout, log4net">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
</log4net>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<httpModules>
<add name="DomainServiceModule" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
<compilation debug="true" targetFramework="4.0" />
<globalization culture="auto" uiCulture="auto" />
<authentication mode="Forms">
<forms name=".Log4NetDemoApplication_ASPXAUTH" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<roleManager enabled="true">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
<properties>
<add name="FriendlyName"/>
</properties>
</profile>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<add name="DomainServiceModule" preCondition="managedHandler"
type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</modules>
</system.webServer>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
在我的AssemblyInfo.cs中,它看起来像这样:
#region Assembly mscorlib.dll, v4.0.30319
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll
#endregion
using System;
using System.Runtime.InteropServices;
namespace System.Reflection
{
// Summary:
// Defines a company name custom attribute for an assembly manifest.
[AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
[ComVisible(true)]
public sealed class AssemblyCompanyAttribute : Attribute
{
// Summary:
// Initializes a new instance of the System.Reflection.AssemblyCompanyAttribute
// class.
//
// Parameters:
// company:
// The company name information.
public AssemblyCompanyAttribute(string company);
// Summary:
// Gets company name information.
//
// Returns:
// A string containing the company name.
public string Company { get; }
}
}
最后但并非最不重要的是,实际代码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace Log4NetDemoApplication.Web.Services
{
/// <summary>
/// Summary description for POWSTestLog
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class POWSTestLog : System.Web.Services.WebService
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
[WebMethod]
public string TestService()
{
log4net.ILog logger = log4net.LogManager.GetLogger(typeof(POWSTestLog));
// log4net.Config.XmlConfigurator.Configure();
logger.Debug("adsölkaölskd");
log.Debug("Debug logging");
log.Info("Info logging");
log.Warn("Warn logging");
log.Error("Error logging");
log.Fatal("Fatal logging");
return "Hello World";
}
}
}
Can't look at this stuff no more =)
Thanks for all your help!
答案 0 :(得分:1)
为什么Configure()方法被注释掉了?应调用它来在web.config中使用您的配置。
log4net.Config.XmlConfigurator.Configure();
您的代码应如下所示
[WebMethod]
public string TestService()
{
log4net.Config.XmlConfigurator.Configure();
var logger = log4net.LogManager.GetLogger(typeof(POWSTestLog));
logger.Debug("Test log entry.");
return "Hello World";
}
答案 1 :(得分:0)
在请求记录器之前,您应该对其进行配置。试一试:
log4net.Config.XmlConfigurator.ConfigureAndWatch(log4netConfigPath);
ILog log4netLogger = LogManager.GetLogger(typeof(MyType));
编辑:我是怎么做的
<强>的web.config:强>
Log4net配置位于/Config/log4net.config.xml
<强>的global.asax 强>
private void Application_Start(object sender, EventArgs e)
{
try
{
var log4netConfigPath = Server.MapPath(
ConfigurationManager.AppSettings["log4netConfigFilePath"]);
if (!String.IsNullOrEmpty(log4netConfigPath) && File.Exists(log4netConfigPath))
{
FileInfo log4netConfig = new FileInfo(log4netConfigPath);
if (log4netConfig != null)
{
log4net.Config.XmlConfigurator.ConfigureAndWatch(log4netConfig);
ILog log4netLogger = LogManager.GetLogger(typeof(Global));
// Then register in IoC container so it would be accessible for dependency injection, etc
// ...
}
}
}
catch (Exception ex)
{
// log error, etc
}
}
log4net.config.xml,文件追加器
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">
<lockingModel type="log4net.Appender.FileAppender+InterProcessLock" />
<param name="Threshold" value="WARN" />
<file type="log4net.Util.PatternString">
<conversionPattern value="logs\lf-%date{yyyy.MM.dd.HH.mm.ss}-[%processid].log" />
</file>
<appendToFile value="true"/>
<rollingStyle value="Composite"/>
<maxSizeRollBackups value="-1"/>
<maximumFileSize value="5MB"/>
<countDirection value="1"/>
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %C{1}-%M - %m%n"/>
</layout>
</appender>