C# 将消息记录到以前创建的日志文件
我正在asp.net网站中使用enterprise library 5.0登录,C# 将消息记录到以前创建的日志文件,c#,asp.net,logging,enterprise-library,C#,Asp.net,Logging,Enterprise Library,我正在asp.net网站中使用enterprise library 5.0登录, 我的web.config文件如下: <?xml version="1.0"?> <configuration> <configSections> <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.
我的
web.config
文件如下:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true"/>
</configSections>
<loggingConfiguration name="FlatFileLogging" tracingEnabled="true"
defaultCategory="General">
<listeners>
<add name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="C:\Logs\2013-06-28 14-21-53.log" header="" footer=""
formatter="Text Formatter" traceOutputOptions="DateTime" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="{timestamp}, {severity}, {message}" name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Flat File Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Flat File Trace Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="true" targetFramework="4.0">
</compilation>
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>
</configuration>
每当我更改日志文件路径并向文件发送日志消息时,日志不会转到新创建的文件。日志消息转到以前设置的文件路径。似乎新的环境并没有立即反映出来
string path = "C:\\Logs\\" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".log";
SetLogFilePath(path);
Logger.Write(message, "General", 1, 0, System.Diagnostics.TraceEventType.Information);
如何刷新新设置以立即编码?如何定义“立即”?如果您的意思是在执行请求的中间,那么我认为您不能通过配置来实现这一点,因为该配置不会刷新该请求。
这是一个基于博客帖子的实现,对我来说似乎很有效。我不会将配置更改写回磁盘,而是在内存中更改
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
EnterpriseLibraryContainer.Current.GetInstance<LogWriter>()
.Write("test", "General");
string path = "C:\\Logs\\anotherlogfile.log";
SetLogFilePath(path);
EnterpriseLibraryContainer.Current.GetInstance<LogWriter>()
.Write("Another test", "General");
}
public void SetLogFilePath(string filePath)
{
ConfigurationFileMap objConfigPath = new ConfigurationFileMap();
// App config file path.
string appPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
objConfigPath.MachineConfigFilename = appPath;
Configuration entLibConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
LoggingSettings loggingSettings = (LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName);
TraceListenerData traceListenerData = loggingSettings.TraceListeners.Get("Flat File Trace Listener");
FlatFileTraceListenerData objFlatFileTraceListenerData = traceListenerData as FlatFileTraceListenerData;
objFlatFileTraceListenerData.FileName = filePath;
IUnityContainer container = new UnityContainer();
container.AddNewExtension<EnterpriseLibraryCoreExtension>();
// Configurator will read Enterprise Library configuration
// and set up the container
UnityContainerConfigurator configurator = new UnityContainerConfigurator(container);
var loggingXmlConfigSource = new SerializableConfigurationSource();
loggingXmlConfigSource.Add(LoggingSettings.SectionName, loggingSettings);
// Configure the container with our own custom logging
EnterpriseLibraryContainer.ConfigureContainer(configurator, loggingXmlConfigSource);
// Wrap in ServiceLocator
IServiceLocator locator = new UnityServiceLocator(container);
// Release lock(s) on existing file(s)
EnterpriseLibraryContainer.Current.GetInstance<LogWriter>().Dispose();
// And set Enterprise Library to use it
EnterpriseLibraryContainer.Current = locator;
}
}
public class SerializableConfigurationSource : IConfigurationSource
{
Dictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>();
public SerializableConfigurationSource()
{
}
public ConfigurationSection GetSection(string sectionName)
{
ConfigurationSection configSection;
if (sections.TryGetValue(sectionName, out configSection))
{
SerializableConfigurationSection section = configSection as SerializableConfigurationSection;
if (section != null)
{
using (StringWriter xml = new StringWriter())
using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(xml))
{
section.WriteXml(xmlwriter);
xmlwriter.Flush();
MethodInfo methodInfo = section.GetType().GetMethod("DeserializeSection", BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo.Invoke(section, new object[] { XDocument.Parse(xml.ToString()).CreateReader() });
return configSection;
}
}
}
return null;
}
public void Add(string sectionName, ConfigurationSection configurationSection)
{
sections[sectionName] = configurationSection;
}
public void AddSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
{
throw new NotImplementedException();
}
public void Remove(string sectionName)
{
sections.Remove(sectionName);
}
public void RemoveSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
{
throw new NotImplementedException();
}
public event EventHandler<ConfigurationSourceChangedEventArgs> SourceChanged;
public void Dispose()
{
}
}
public分部类\u默认值:System.Web.UI.Page
{
受保护的无效页面加载(对象发送方、事件参数e)
{
EnterpriseLibraryContainer.Current.GetInstance()
.编写(“测试”、“一般”);
string path=“C:\\Logs\\anotherlogfile.log”;
SetLogFilePath(路径);
EnterpriseLibraryContainer.Current.GetInstance()
.编写(“另一项测试”、“一般测试”);
}
public void SetLogFilePath(字符串文件路径)
{
ConfigurationFileMap objConfigPath=新的ConfigurationFileMap();
//应用程序配置文件路径。
字符串appPath=AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
objConfigPath.MachineConfigFilename=appPath;
Configuration entLibConfig=System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(“~”);
LoggingSettings LoggingSettings=(LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName);
TraceListenerData TraceListenerData=loggingSettings.TraceListeners.Get(“平面文件跟踪侦听器”);
FlatFileTraceListenerData objFlatFileTraceListenerData=作为FlatFileTraceListenerData的traceListenerData;
objFlatFileTraceListenerData.FileName=文件路径;
IUnityContainer容器=新的UnityContainer();
container.AddNewExtension();
//Configurator将读取企业库配置
//并设置容器
UnityContainerConfiguration配置器=新的UnityContainerConfiguration(容器);
var loggingXmlConfigSource=新的SerializableConfigurationSource();
loggingXmlConfigSource.Add(LoggingSettings.SectionName,LoggingSettings);
//使用我们自己的自定义日志配置容器
EnterpriseLibraryContainer.ConfigureContainer(configurator,loggingXmlConfigSource);
//包裹式服务定位器
IServiceLocator=新的UnityServiceLocator(容器);
//释放现有文件上的锁
EnterpriseLibraryContainer.Current.GetInstance().Dispose();
//并将企业库设置为使用它
EnterpriseLibraryContainer.Current=定位器;
}
}
公共类SerializableConfigurationSource:IConfigurationSource
{
字典部分=新字典();
public SerializableConfigurationSource()
{
}
公共配置节GetSection(字符串节名)
{
配置部分配置部分;
if(sections.TryGetValue(sectionName,out configSection))
{
SerializableConfigurationSection=configSection作为SerializableConfigurationSection;
if(节!=null)
{
使用(StringWriter xml=new StringWriter())
使用(XmlWriter=System.Xml.XmlWriter.Create(Xml))
{
第.WriteXml节(xmlwriter);
xmlwriter.Flush();
MethodInfo MethodInfo=section.GetType().GetMethod(“反序列化section”,BindingFlags.NonPublic | BindingFlags.Instance);
调用(节,新对象[]{XDocument.Parse(xml.ToString()).CreateReader()});
返回段;
}
}
}
返回null;
}
public void Add(string section name,ConfigurationSection ConfigurationSection)
{
节[sectionName]=配置节;
}
public void AddSectionChangeHandler(字符串sectionName、ConfigurationChangedEventHandler处理程序)
{
抛出新的NotImplementedException();
}
公共无效删除(字符串节名)
{
节。删除(节名称);
}
public void RemoveSectionChangeHandler(字符串节名称,ConfigurationChangedEventHandler处理程序)
{
抛出新的NotImplementedException();
}
公共事件事件处理程序源已更改;
公共空间处置()
{
}
}
还是发生了同样的事情,当我第一次生成文件名并使用上面的SetLogFilePath
函数设置日志文件时,它工作得很好,第二次生成日志文件路径并设置日志文件时,日志会转到先前创建的日志文件。我似乎工作正常:我使用了Ent.Lib 5.0.414.0,这(全部)使用您的代码需要程序集吗?使用UnityContainerConfiguration、EnterpriseLibraryContainer、IServiceLocator等需要哪些组件?非常感谢。你试过兰迪·利维的答案吗?您是否使用Ent.lib5.0.414.0?
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
EnterpriseLibraryContainer.Current.GetInstance<LogWriter>()
.Write("test", "General");
string path = "C:\\Logs\\anotherlogfile.log";
SetLogFilePath(path);
EnterpriseLibraryContainer.Current.GetInstance<LogWriter>()
.Write("Another test", "General");
}
public void SetLogFilePath(string filePath)
{
ConfigurationFileMap objConfigPath = new ConfigurationFileMap();
// App config file path.
string appPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
objConfigPath.MachineConfigFilename = appPath;
Configuration entLibConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
LoggingSettings loggingSettings = (LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName);
TraceListenerData traceListenerData = loggingSettings.TraceListeners.Get("Flat File Trace Listener");
FlatFileTraceListenerData objFlatFileTraceListenerData = traceListenerData as FlatFileTraceListenerData;
objFlatFileTraceListenerData.FileName = filePath;
IUnityContainer container = new UnityContainer();
container.AddNewExtension<EnterpriseLibraryCoreExtension>();
// Configurator will read Enterprise Library configuration
// and set up the container
UnityContainerConfigurator configurator = new UnityContainerConfigurator(container);
var loggingXmlConfigSource = new SerializableConfigurationSource();
loggingXmlConfigSource.Add(LoggingSettings.SectionName, loggingSettings);
// Configure the container with our own custom logging
EnterpriseLibraryContainer.ConfigureContainer(configurator, loggingXmlConfigSource);
// Wrap in ServiceLocator
IServiceLocator locator = new UnityServiceLocator(container);
// Release lock(s) on existing file(s)
EnterpriseLibraryContainer.Current.GetInstance<LogWriter>().Dispose();
// And set Enterprise Library to use it
EnterpriseLibraryContainer.Current = locator;
}
}
public class SerializableConfigurationSource : IConfigurationSource
{
Dictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>();
public SerializableConfigurationSource()
{
}
public ConfigurationSection GetSection(string sectionName)
{
ConfigurationSection configSection;
if (sections.TryGetValue(sectionName, out configSection))
{
SerializableConfigurationSection section = configSection as SerializableConfigurationSection;
if (section != null)
{
using (StringWriter xml = new StringWriter())
using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(xml))
{
section.WriteXml(xmlwriter);
xmlwriter.Flush();
MethodInfo methodInfo = section.GetType().GetMethod("DeserializeSection", BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo.Invoke(section, new object[] { XDocument.Parse(xml.ToString()).CreateReader() });
return configSection;
}
}
}
return null;
}
public void Add(string sectionName, ConfigurationSection configurationSection)
{
sections[sectionName] = configurationSection;
}
public void AddSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
{
throw new NotImplementedException();
}
public void Remove(string sectionName)
{
sections.Remove(sectionName);
}
public void RemoveSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler)
{
throw new NotImplementedException();
}
public event EventHandler<ConfigurationSourceChangedEventArgs> SourceChanged;
public void Dispose()
{
}
}