Search Results

Search found 28 results on 2 pages for 'xmlconfigurator'.

Page 1/2 | 1 2  | Next Page >

  • log4net initialisation

    - by Ruben Bartelink
    I've looked hard for duplicates but have to ask the following, no matter how basic it may seem, to get it clear once and for all! In a fresh Console app using log4net version 1.2.10.0 on VS28KSP1 on 64 bit W7, I have the following code:- using log4net; using log4net.Config; namespace ConsoleApplication1 { class Program { static readonly ILog _log = LogManager.GetLogger(typeof(Program)); static void Main(string[] args) { _log.Info("Ran"); } } } In my app.config, I have: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="Program.log" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="[%username] %date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <root> <level value="DEBUG" /> <appender-ref ref="RollingFileAppender" /> </root> </log4net> </configuration> This doesnt write anything, unless I either add an attribute: [ assembly:XmlConfigurator ] Or explicitly initialise it in Main(): _log.Info("This will not go to the log"); XmlConfigurator.Configure(); _log.Info("Ran"); This raises the following questions: I'm almost certain I've seen it working somewhere on some version of log4net without the addition of the assembly attribute or call in Main. Can someone assure me I'm not imagining that? Can someone please point me to where in the doc it explicitly states that both the config section and the initialisation hook are required - hopefully with an explanation of when this changed, if it did? I can easily imagine why this might be the policy -- having the initialisation step explicit to avoid surprises etc., it's just that I seem to recall this not always being the case... (And normally I have the config in a separate file, which generally takes configsections out of the picture)

    Read the article

  • How Can I tell where log4net thinks it's getting it's config file from?

    - by Mike
    Hi, I have the following log from the log4net debug log: log4net: DefaultRepositorySelector: repository [log4net-default-repository] already exists, using repository type [log4net.Repository.Hierarchy.Hierarchy] log4net: XmlConfigurator: configuring repository [log4net-default-repository] using file [log4net.config] watching for file updates log4net: XmlConfigurator: configuring repository [log4net-default-repository] using file [log4net.config] log4net: XmlConfigurator: configuring repository [log4net-default-repository] using stream log4net:ERROR XmlConfigurator: Error while loading XML configuration System.Xml.XmlException: ' ' is an unexpected token. The expected token is ''. Line 7, position 184. at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.Throw(String res, String[] args) at System.Xml.XmlTextReaderImpl.ThrowUnexpectedToken(String expectedToken1, String expectedToken2) at System.Xml.XmlTextReaderImpl.ThrowUnexpectedToken(Int32 pos, String expectedToken1, String expectedToken2) at System.Xml.XmlTextReaderImpl.ParseAttributes() at System.Xml.XmlTextReaderImpl.ParseElement() at System.Xml.XmlTextReaderImpl.ParseElementContent() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.XmlTextReader.Read() at System.Xml.XmlValidatingReaderImpl.Read() at System.Xml.XmlValidatingReader.Read() at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace) at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc) at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace) at System.Xml.XmlDocument.Load(XmlReader reader) at log4net.Config.XmlConfigurator.Configure(ILoggerRepository repository, Stream configStream) The only problem is, I have no idea where it thinks it's getting this log4net.config file, since in my AssemblyInfo.cs I have defined it to be: [assembly: log4net.Config.XmlConfigurator(ConfigFile = "api4net.config", Watch = true)] Is there an easy way to determine where log4net is loading this mystical log4net.config that has some xml errors?

    Read the article

  • Best practice to include log4Net external config file in ASP.NET

    - by Martin Buberl
    I have seen at least two ways to include an external log4net config file in an ASP.NET web application: Having the following attribute in your AssemblyInfo.cs file: [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log.config", Watch = true)] Calling the XmlConfigurator in the Global.asax.cs: protected void Application_Start() { XmlConfigurator.Configure(new FileInfo("Log.config")); } What would be the best practice to do it?

    Read the article

  • Can log4net appenders be defined in their own XML files?

    - by ladenedge
    I want to define a handful of (ADO.NET) appenders in my library, but allow users of my library to configure the use of those appenders. Something like this seems to be what I want: XmlConfigurator.Configure(appenderStream1); XmlConfigurator.Configure(appenderStream2); XmlConfigurator.Configure(); But that doesn't seem work, in spite of the debug output containing messages like this: Configuration update mode [Merge]. What is the right way to do this? Or, is there an alternative to asking users to duplicate large chunks of XML configuration?

    Read the article

  • Configuring log4net appenders via XML file *and* code

    - by Dave
    I started to play with log4net today and so far, I really like it. In order to preserve our current logging functionality, the app needs to create a new log file whenever the application is started. The log file name has the date and time stamp encoded in it. Currently, I've got log4net configured via an XmlConfigurator, which works great, except that the filename for my RollingFileAppender is hardcoded in the configuration XML file. I'd like to continue to use the XmlConfigurator, but after calling Configure(), I want to get at the RollingFileAppender and, in code, change its file value to be a dynamically-generated string. The sample documentation online seems to be down right now, but I've poked through the SDK reference, and it looks like I could use the Heirarchy and GetAppenders() to do what I need to do. Am I on the right track?

    Read the article

  • log4net affecting other projects which don't even use it

    - by Graeme
    I'm seeing something really strange happening with some projects I'm working on. I used log4net in an MVC web site and this was working great. I then was working on a totally unrelated Console application which uses the SharePoint API and as soon as I include the following line (other lines don't cause the problem) SPLimitedWebPartManager spWebPartManager = web.GetLimitedWebPartManager("http://blah/blah.aspx?PageView=Shared", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); I get the following message in the console app log4net:ERROR XmlConfigurator: Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and < configSections> elements. The configuration section should look like: <section n ame="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" / > log4net:ERROR XmlConfigurator: Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the <log4net> and < configSections> elements. The configuration section should look like: <section n ame="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" / > I get this twice after a small delay. The delay is probably the request to get the web part manager from the page but I'm not sure why this log4net error is showing up in this project. I've gone through the code and bin folders etc. and found no trace of any log4net mentions. Any ideas why this might be happening?

    Read the article

  • log4net creates log file but does not write to it (windows service in C#)

    - by user1825172
    I am trying to use basic logging for a windows service. I added the reference to log4net I added the following in AssemblyInfo.cs: [assembly: log4net.Config.XmlConfigurator(Watch = true)] I added the following to my App.config: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" requirePermission="false" /> </configSections> <!-- Log4net Logging Setup --> <log4net> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender,log4net"> <file value="c:\\CGSD\\log\\logfile.txt" /> <appendToFile value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %level %logger - %message%newline" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="INFO" /> <levelMax value="FATAL" /> </filter> </appender> <root> <level value="ALL"/> <appender-ref ref="RollingFileAppender"/> </root> </log4net> </configuration> I have the following code in my service: log4net.Config.XmlConfigurator.Configure(); log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program)); log.Debug("test"); the file c:\CGSD\log\logfile.txt is created but nothing is ever written to it. i've been thru the forums all day trying to trac this one down, but if i overlooked an already posted solution i apologize. thx!

    Read the article

  • log4net configuration problem

    - by user177883
    I have a seperate Log4Net.config file. I added [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)] to AssemblyInfo.cs When I run the application with debug mode, lognet is logging. When i publish the application to IIS, lognet is not logging anything. I have the followings also : BasicConfigurator.Configure(); // in a method private static readonly ILog _logger = LogManager.GetLogger(typeof(_Default)); // for the instance What would be the reason for this?

    Read the article

  • How to use #if directives in C#(3.0)

    - by Newbie
    I just found two piece of code #if CONSOLE // defined by the console version using ournamespace.FactoryInitializer; #endif and #if _NET_1_1 log4net.Config.DOMConfigurator.ConfigureAndWatch(new System.IO.FileInfo(s) ); #else log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(s) ); #endif Can any one please tell me with a running sample( please provide a simple one) what is the significance of those code snippets and when and how to use those? Thanks.

    Read the article

  • Log4Net and GAC - How to reference Configuraition Files?

    - by Adam
    Hello all I am using log4net during my development, as as part of a project constraint, I now need to add it to the Global Assembly Cache. The logging definitions are in a file Log4Net.xml. That file is referenced in my assemblyinfo as: [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.xml", Watch = true)]. So long as the xml file was in the same directory as the log4net.dll, everything has been working fine. However now that I've added log4net to the GAC, it is no longer picking up the xml file. Does anyone know what I need to change in order to have it pick up the XML file again? Is hardcoding the patch in the assembly reference the only way? Many thanks

    Read the article

  • log4net - configure using multiple configuration files

    - by Gai
    Hi, I have an application consisting of a host and pluggable modules (plugins). I want to be able to configure log4net for the host and for each of the other modules. Each of them should have its own configuration file and each will log to a different file. Only the host has an App.config file. The plugins have their own config file containing the log4net config sections. Calling XmlConfigurator.Configure from one of the plugins overrides the host's app.config log4net definitions. Is there an easy way to append configurations instead of overriding them? Thanks, Gai.

    Read the article

  • log4Net EventlogAppender does not work for Asp.Net 2.0 WebSite?

    - by Amitabh
    I have configured log4Net EventLogAppender for Asp.Net 2.0. However it does not log anything. I have following in my Web.Config. <log4net> <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender"> <param name="LogName" value="Test Log" /> <param name="ApplicationName" value="Test-Web" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <root> <priority value="ERROR"/> <appender-ref ref="EventLogAppender"/> </root> <logger name="NHibernate"> <level value="ERROR" /> <appender-ref ref="EventLogAppender" /> </logger> </log4net> I already have Test-Log Event Log created and AspNet user has permission on the Event Log registry entry. I also have log4Net configured in Global.asax Application_Start. log4net.Config.XmlConfigurator.Configure();

    Read the article

  • What am I missing with log4net - No log file created

    - by Saif Khan
    I am trying to use log4net in a VB.NET app for some unknown reason it's not creating the log file. Here is my app.config <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net> <appender name="FileAppender" type="log4net.Appender.FileAppender"> <file value="c:\log-file.txt" /> <appendToFile value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <root> <level value="ALL" /> <appender-ref ref="FileAppender" /> </root> </log4net> </configuration> Here is the app code Imports log4net Public Class Form1 Dim log As ILog Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click log.Error("test") End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load log4net.Config.XmlConfigurator.Configure() log = log4net.LogManager.GetLogger("TestThings") End Sub End Class "TestThings" is the name of the VS project. What am I missing?

    Read the article

  • NullReferenceException when initializing NServiceBus within web application Application_Start method

    - by SteveBering
    I am running the 2.0 RTM of NServiceBus and am getting a NullReferenceException when my MessageModule binds the CurrentSessionContext to my NHibernate sessionfactory. From within my Application_Start, I call the following method: public static void WithWeb(IUnityContainer container) { log4net.Config.XmlConfigurator.Configure(); var childContainer = container.CreateChildContainer(); childContainer.RegisterInstance<ISessionFactory>(NHibernateSession.SessionFactory); var bus = NServiceBus.Configure.WithWeb() .UnityBuilder(childContainer) .Log4Net() .XmlSerializer() .MsmqTransport() .IsTransactional(true) .PurgeOnStartup(false) .UnicastBus() .ImpersonateSender(false) .LoadMessageHandlers() .CreateBus(); var activeBus = bus.Start(); container.RegisterInstance(typeof(IBus), activeBus); } When the bus is started, my message module starts with the following: public void HandleBeginMessage() { try { CurrentSessionContext.Bind(_sessionFactory.OpenSession()); } catch (Exception e) { _log.Error("Error occurred in HandleBeginMessage of NHibernateMessageModule", e); throw; } } In looking at my log, we are logging the following error when the bind method is called: System.NullReferenceException: Object reference not set to an instance of an object. at NHibernate.Context.WebSessionContext.GetMap() at NHibernate.Context.MapBasedSessionContext.set_Session(ISession value) at NHibernate.Context.CurrentSessionContext.Bind(ISession session) Apparently, there is some issue in getting access to the HttpContext. Should this call to configure NServiceBus occur later in the lifecycle than Application_Start? Or is there another workaround that others have used to get handlers working within an Asp.NET Web application? Thanks, Steve

    Read the article

  • Log4net Logging Problem : Very simple file appender logging not working

    - by contactmatt
    Here's my web.config information <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <root> <level value="ALL" /> </root> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="c:\temp\log-file.txt" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.SimpleLayout" /> </appender> </log4net> ... Here's the code that initalizes the logger protected void SendMessage() { log4net.Config.XmlConfigurator.Configure(); ILog log = LogManager.GetLogger(typeof(Contact)); ... log.Info("here we go!"); log.Debug("debug afasf"); ... } it doesn't work, no matter what I seem to do. I am referencing the 'log4net.dll' correctly, and by debugging the application i can see that the log object is getting initiated properly. This is a asp.net 3.5 framework web project. Any ideas/suggestions? I thought originally this error may be due to a file write permission constraint, but that doesn't seem to be the case (or so I think).

    Read the article

  • Stuck trying to get Log4Net to work with Dependency Injection

    - by Pure.Krome
    I've got a simple winform test app i'm using to try some Log4Net Dependency Injection stuff. I've made a simple interface in my Services project :- public interface ILogging { void Debug(string message); // snip the other's. } Then my concrete type will be using Log4Net... public class Log4NetLogging : ILogging { private static ILog Log4Net { get { return LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); } } public void Debug(string message) { if (Log4Net.IsDebugEnabled) { Log4Net.Debug(message); } } } So far so good. Nothing too hard there. Now, in a different project (and therefore namesapce), I try and use this ... public partial class Form1 : Form { public Form1() { FileInfo fileInfo = new FileInfo("Log4Net.config"); log4net.Config.XmlConfigurator.Configure(fileInfo); } private void Foo() { // This would be handled with DI, but i've not set it up // (on the constructor, in this code example). ILogging logging = new Log4NetLogging(); logging.Debug("Test message"); } } Ok .. also pretty simple. I've hardcoded the ILogging instance but that is usually dependency injected via the constructor. Anyways, when i check this line of code... return LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); the DeclaringType type value is of the Service namespace, not the type of the Form (ie. X.Y.Z.Form1) which actually called the method. Without passing the type INTO method as another argument, is there anyway using reflection to figure out the real method that called it?

    Read the article

  • I cannot make log4net work in my web application :(

    - by vtortola
    Hi, I'm trying to set up log4net but I cannot make it work. I've put this in my Web.config: <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="logfile.log" /> <appendToFile value="true" /> <rollingStyle value="Composite" /> <maxSizeRollBackups value="14" /> <maximumFileSize value="15000KB" /> <datePattern value="yyyyMMdd" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <root> <level value="DEBUG" /> <appender-ref ref="RollingFileAppender" /> <appender-ref ref="TraceAppender" /> </root> (StackOverflow is not rendering correctly the code I've pasted, I don't know why) Then, in my code I execute: log4net.Config.XmlConfigurator.Configure(new FileInfo(HttpContext.Current.Server.MapPath("~/Web.config"))); ILog log = LogManager.GetLogger("MainLogger"); if(log.IsDebugEnabled) log.Debug("lalala"); But nothing happen. I check the "log" variable, and contains an LogImpl object, that has all the logging levels enabled. I get no error or configuration warning, I cannot see any file in the root, in the bin or anywhere. What do I have to do to make it work? Cheers.

    Read the article

  • Best practices for creating a logger library using log4net. Is

    - by VolleyBall Player
    My goal is to create a log4net library that can be shared across multiple projects. In my solution which is in .net 4.0, I created a class library called Logger and referenced it from web project. Now I created a logger.config in the class library and put all the configuration in the logger.config file. I then used [assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFile = "Logger.config")] When I run the web app nothing is getting logged. So I added this line of code in web.config <add key="log4net.Internal.Debug" value="true"/> which gave me debugging info and error information Failed to find configuration section 'log4net' in the application's .config file. Check your .config file for the and elements. The configuration section should look like: I moved the configuration from logger.config to web.config and everything seems to work fine. I don't want the log4net configuration in web.config but have it logger.config as a cleaner approach. The goal is to make other projects use this library and not have to worry about configuration in every project. Now the question is, How do I do this? What am I doing wrong? Any suggestion with code example will be beneficial to everyone. FYI, I am using structure map IOC to reslove the logger before logging to it.

    Read the article

  • "No message serializer has been configured" error when starting NServiceBus endpoint

    - by SteveBering
    My GenericHost hosted service is failing to start with the following message: 2010-05-07 09:13:47,406 [1] FATAL NServiceBus.Host.Internal.GenericHost [(null)] <(null) - System.InvalidOperationException: No message serializer has been con figured. at NServiceBus.Unicast.Transport.Msmq.MsmqTransport.CheckConfiguration() in d:\BuildAgent-02\work\672d81652eaca4e1\src\impl\unicast\NServiceBus.Unicast.Msmq\ MsmqTransport.cs:line 241 at NServiceBus.Unicast.Transport.Msmq.MsmqTransport.Start() in d:\BuildAgent-02\work\672d81652eaca4e1\src\impl\unicast\NServiceBus.Unicast.Msmq\MsmqTransport .cs:line 211 at NServiceBus.Unicast.UnicastBus.NServiceBus.IStartableBus.Start(Action startupAction) in d:\BuildAgent-02\work\672d81652eaca4e1\src\unicast\NServiceBus.Uni cast\UnicastBus.cs:line 694 at NServiceBus.Unicast.UnicastBus.NServiceBus.IStartableBus.Start() in d:\BuildAgent-02\work\672d81652eaca4e1\src\unicast\NServiceBus.Unicast\UnicastBus.cs:l ine 665 at NServiceBus.Host.Internal.GenericHost.Start() in d:\BuildAgent-02\work\672d81652eaca4e1\src\host\NServiceBus.Host\Internal\GenericHost.cs:line 77 My endpoint configuration looks like: public class ServiceEndpointConfiguration : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization { public void Init() { // build out persistence infrastructure var sessionFactory = Bootstrapper.InitializePersistence(); // configure NServiceBus infrastructure var container = Bootstrapper.BuildDependencies(sessionFactory); // set up logging log4net.Config.XmlConfigurator.Configure(); Configure.With() .Log4Net() .UnityBuilder(container) .XmlSerializer(); } } And my app.config looks like: <configSections> <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" /> <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" /> <section name="Logging" type="NServiceBus.Config.Logging, NServiceBus.Core" /> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" /> </configSections> <Logging Threshold="DEBUG" /> <MsmqTransportConfig InputQueue="NServiceBus.ServiceInput" ErrorQueue="NServiceBus.Errors" NumberOfWorkerThreads="1" MaxRetries="2" /> <UnicastBusConfig DistributorControlAddress="" DistributorDataAddress="" ForwardReceivedMessagesTo="NServiceBus.Auditing"> <MessageEndpointMappings> <!-- publishers don't need to set this for their own message types --> </MessageEndpointMappings> </UnicastBusConfig> <connectionStrings> <add name="Db" connectionString="Data Source=..." providerName="System.Data.SqlClient" /> </connectionStrings> <log4net debug="true"> <root> <level value="INFO"/> </root> <logger name="NHibernate"> <level value="ERROR" /> </logger> </log4net> This has worked in the past, but seems to be failing when the generic host starts. My endpoint configuration is below, along with the app.config for the service. What is strange is that in my endpoint configuration, I am specifying to use the XmlSerializer for message serialization. I don't see any other errors in the console output preceding the error message. What am I missing? Thanks, Steve

    Read the article

  • log4net not logging with a mixture of .net 1.1 and .net 3.5

    - by Jim P
    Hi All, I have an iis server on a windows 2003 production machine that will not log using log4net in the .net3.5 web application. Log4net works fine in the 1.1 apps using log4net version 1.2.9.0 and but not the 3.5 web app. The logging works fine in a development and staging environment but not in production. It does not error and I receive no events logged in the event viewer and don't know where to look next. I have tried both versions of log4net (1.2.9.0 and 1.2.10.0) and both work in development and staging but not in production. For testing purposes I have created just a single page application that just echos back the time when the page is hit and also is supposed to log to my logfile using log4net. Here is my web.config file: <configSections> <!-- LOG4NET Configuration --> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" requirePermission="false" /> </configSections> <log4net debug="true"> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="D:\DIF\Logs\TestApp\TestApp_"/> <param name="AppendToFile" value="true"/> <param name="RollingStyle" value="Date"/> <param name="DatePattern" value="yyyyMMdd\.\l\o\g"/> <param name="StaticLogFileName" value="false"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%date{HH:mm:ss} %C::%M [%-5level] - %message%newline"/> </layout> </appender> <root> <level value="ALL"/> <appender-ref ref="RollingFileAppender"/> </root> </log4net> Here is my log4net initialization: // Logging for the application private static ILog mlog = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected void Application_Start(object sender, EventArgs e) { try { // Start the configuration of the Logging XmlConfigurator.Configure(); mlog.Info("Started logging for the TestApp Application."); } catch (Exception ex) { throw; } } Any help would be greatly appreciated. Thanks, Jim

    Read the article

  • log4net: what am I doing wrong?

    - by Berryl
    Being a log4net newb / boob I just copied lines from an NHibernate example project where I can see the log.txt file is updated. Is there a quick answer why mine isn't creating the file? Cheers, Berryl [assembly: log4net.Config.XmlConfigurator(Watch = true)] I saw another post here saying this should go in AssemblyInfo, but in the example project this is just another line in a static helper class. Not wanting to 'mess with' assemblyInfo I also put this in a static helper, along with the following to actually log in the same static helper class: private static readonly log4net.ILog _log = log4net.LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType ); And in app.config, I have <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> </configSections> <!-- This section contains the log4net configuration settings --> <log4net> <!-- Define an output appender (where the logs can go) --> <appender name="LogFileAppender" type="log4net.Appender.FileAppender, log4net"> <param name="File" value="log.txt" /> <param name="AppendToFile" value="false" /> <layout type="log4net.Layout.PatternLayout, log4net"> <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n" /> </layout> </appender> <appender name="LogDebugAppender" type="log4net.Appender.DebugAppender, log4net"> <layout type="log4net.Layout.PatternLayout, log4net"> <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n"/> </layout> </appender> <!-- Setup the root category, set the default priority level and add the appender(s) (where the logs will go) --> <root> <priority value="ALL" /> <appender-ref ref="LogFileAppender" /> <appender-ref ref="LogDebugAppender"/> </root> <!-- Specify the level for some specific namespaces --> <!-- Level can be : ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF --> <logger name="NHibernate"> <level value="ALL" /> </logger> </log4net>

    Read the article

  • log4net logging problem

    - by Dotnet_user
    Hello everyone, I'm not sure if this is the right forum to post this question. But I'm just hoping someone here might have used log4net in the past, so hoping to get some help. I'm using log4net to log my exceptions. The configuration settings look like this: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net debug="false"> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="C:\Logs\sample.log" /> <appendToFile value="true"/> <rollingStyle value="Size"/> <maxSizeRollBackups value="10"/> <maximumFileSize value="10MB"/> <staticLogFileName value="true"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%-5level %date %logger.%method[line %line] - %message%newline"/> </layout> </appender> <root> <level value="INFO"/> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> </configuration> I started out by adding this configuration to web.config, but I got an error (VS studio could not find a schema for log4net-"Could not find schema information for the element log4net"). So I followed this link (http://stackoverflow.com/questions/174430/log4net-could-not-find-schema-information-messages) and configured my settings in a separate xml file and added the following line of code in my AssemblyInfo.cs: [assembly: log4net.Config.XmlConfigurator(ConfigFile = "xmlfile.xml", Watch = true)] And in the actual code, I placed this line: public void CreateUser(String username, String password) { try { log.Info("Inside createuser"); //code for creating user } catch(exception e) { log.Info("something happened in create user", e); } } The problem is that the log file is not being created. I can't see anything inside C:\Logs. Can anybody tell me what I'm doing wrong here? Any suggestions/inputs will be very helpful. Thank you all in advance.

    Read the article

  • how to insert into database from stored procedure in log4net?

    - by Samreen
    I have to log thread context properties like this: string logFilePath = AppDomain.CurrentDomain.BaseDirectory + "log4netconfig.xml"; FileInfo finfo = new FileInfo(logFilePath); log4net.Config.XmlConfigurator.ConfigureAndWatch(finfo); ILog logger = LogManager.GetLogger("Exception.Logging"); log4net.ThreadContext.Properties["MESSAGE"] = exception.Message; log4net.ThreadContext.Properties["MODULE"] = "module1"; log4net.ThreadContext.Properties["COMPONENT"] = "component1"; logger.Debug("test"); and the configuration file is: <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> </configSections> <log4net> <logger name="Exception.Logging" level="Debug"> <appender-ref ref="AdoNetAppender"/> </logger> <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender"> <connectionString value="Data Source=xe;User ID=test;Password=test;" /> <connectionType value="System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <bufferSize value="10000"/> <commandText value="Log_Exception_Pkg.Insert_Log" /> <commandType value="StoredProcedure" /> <parameter> <parameterName value="@p_Error_Message" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{MESSAGE}"/> </layout> </parameter> <parameter> <parameterName value="@p_Module" /> <dbType value="String" /> <size value="225" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{MODULE}"/> </layout> </parameter> <parameter> <parameterName value="@p_Component" /> <dbType value="String" /> <size value="225" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{COMPONENT}"/> </layout> </parameter> </appender> </log4net> </configuration> But its not inserting them in the database. How can I get that to work?

    Read the article

  • MvcExtensions – Bootstrapping

    - by kazimanzurrashid
    When you create a new ASP.NET MVC application you will find that the global.asax contains the following lines: namespace MvcApplication1 { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } } } As the application grows, there are quite a lot of plumbing code gets into the global.asax which quickly becomes a design smell. Lets take a quick look at the code of one of the open source project that I recently visited: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute("Default","{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }); } protected override void OnApplicationStarted() { Error += OnError; EndRequest += OnEndRequest; var settings = new SparkSettings() .AddNamespace("System") .AddNamespace("System.Collections.Generic") .AddNamespace("System.Web.Mvc") .AddNamespace("System.Web.Mvc.Html") .AddNamespace("MvcContrib.FluentHtml") .AddNamespace("********") .AddNamespace("********.Web") .SetPageBaseType("ApplicationViewPage") .SetAutomaticEncoding(true); #if DEBUG settings.SetDebug(true); #endif var viewFactory = new SparkViewFactory(settings); ViewEngines.Engines.Add(viewFactory); #if !DEBUG PrecompileViews(viewFactory); #endif RegisterAllControllersIn("********.Web"); log4net.Config.XmlConfigurator.Configure(); RegisterRoutes(RouteTable.Routes); Factory.Load(new Components.WebDependencies()); ModelBinders.Binders.DefaultBinder = new Binders.GenericBinderResolver(Factory.TryGet<IModelBinder>); ValidatorConfiguration.Initialize("********"); HtmlValidationExtensions.Initialize(ValidatorConfiguration.Rules); } private void OnEndRequest(object sender, System.EventArgs e) { if (((HttpApplication)sender).Context.Handler is MvcHandler) { CreateKernel().Get<ISessionSource>().Close(); } } private void OnError(object sender, System.EventArgs e) { CreateKernel().Get<ISessionSource>().Close(); } protected override IKernel CreateKernel() { return Factory.Kernel; } private static void PrecompileViews(SparkViewFactory viewFactory) { var batch = new SparkBatchDescriptor(); batch.For<HomeController>().For<ManageController>(); viewFactory.Precompile(batch); } As you can see there are quite a few of things going on in the above code, Registering the ViewEngine, Compiling the Views, Registering the Routes/Controllers/Model Binders, Settings up Logger, Validations and as you can imagine the more it becomes complex the more things will get added in the application start. One of the goal of the MVCExtensions is to reduce the above design smell. Instead of writing all the plumbing code in the application start, it contains BootstrapperTask to register individual services. Out of the box, it contains BootstrapperTask to register Controllers, Controller Factory, Action Invoker, Action Filters, Model Binders, Model Metadata/Validation Providers, ValueProvideraFactory, ViewEngines etc and it is intelligent enough to automatically detect the above types and register into the ASP.NET MVC Framework. Other than the built-in tasks you can create your own custom task which will be automatically executed when the application starts. When the BootstrapperTasks are in action you will find the global.asax pretty much clean like the following: public class MvcApplication : UnityMvcApplication { public void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e) { Check.Argument.IsNotNull(e, "e"); HttpException exception = e.Exception.GetBaseException() as HttpException; if ((exception != null) && (exception.GetHttpCode() == (int)HttpStatusCode.NotFound)) { e.Dismiss(); } } } The above code is taken from my another open source project Shrinkr, as you can see the global.asax is longer cluttered with any plumbing code. One special thing you have noticed that it is inherited from the UnityMvcApplication rather than regular HttpApplication. There are separate version of this class for each IoC Container like NinjectMvcApplication, StructureMapMvcApplication etc. Other than executing the built-in tasks, the Shrinkr also has few custom tasks which gets executed when the application starts. For example, when the application starts, we want to ensure that the default users (which is specified in the web.config) are created. The following is the custom task that is used to create those default users: public class CreateDefaultUsers : BootstrapperTask { protected override TaskContinuation ExecuteCore(IServiceLocator serviceLocator) { IUserRepository userRepository = serviceLocator.GetInstance<IUserRepository>(); IUnitOfWork unitOfWork = serviceLocator.GetInstance<IUnitOfWork>(); IEnumerable<User> users = serviceLocator.GetInstance<Settings>().DefaultUsers; bool shouldCommit = false; foreach (User user in users) { if (userRepository.GetByName(user.Name) == null) { user.AllowApiAccess(ApiSetting.InfiniteLimit); userRepository.Add(user); shouldCommit = true; } } if (shouldCommit) { unitOfWork.Commit(); } return TaskContinuation.Continue; } } There are several other Tasks in the Shrinkr that we are also using which you will find in that project. To create a custom bootstrapping task you have create a new class which either implements the IBootstrapperTask interface or inherits from the abstract BootstrapperTask class, I would recommend to start with the BootstrapperTask as it already has the required code that you have to write in case if you choose the IBootstrapperTask interface. As you can see in the above code we are overriding the ExecuteCore to create the default users, the MVCExtensions is responsible for populating the  ServiceLocator prior calling this method and in this method we are using the service locator to get the dependencies that are required to create the users (I will cover the custom dependencies registration in the next post). Once the users are created, we are returning a special enum, TaskContinuation as the return value, the TaskContinuation can have three values Continue (default), Skip and Break. The reason behind of having this enum is, in some  special cases you might want to skip the next task in the chain or break the complete chain depending upon the currently running task, in those cases you will use the other two values instead of the Continue. The last thing I want to cover in the bootstrapping task is the Order. By default all the built-in tasks as well as newly created task order is set to the DefaultOrder(a static property), in some special cases you might want to execute it before/after all the other tasks, in those cases you will assign the Order in the Task constructor. For Example, in Shrinkr, we want to run few background services when the all the tasks are executed, so we assigned the order as DefaultOrder + 1. Here is the code of that Task: public class ConfigureBackgroundServices : BootstrapperTask { private IEnumerable<IBackgroundService> backgroundServices; public ConfigureBackgroundServices() { Order = DefaultOrder + 1; } protected override TaskContinuation ExecuteCore(IServiceLocator serviceLocator) { backgroundServices = serviceLocator.GetAllInstances<IBackgroundService>().ToList(); backgroundServices.Each(service => service.Start()); return TaskContinuation.Continue; } protected override void DisposeCore() { backgroundServices.Each(service => service.Stop()); } } That’s it for today, in the next post I will cover the custom service registration, so stay tuned.

    Read the article

  • Problem with initializing a type with WinsdorContainer

    - by the_drow
    public ApplicationView(string[] args) { InitializeComponent(); string configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config"); FileInfo configFileInfo = new FileInfo(configFilePath); XmlConfigurator.ConfigureAndWatch(configFileInfo); IConfigurationSource configSource = ConfigurationManager.GetSection("ActiveRecord") as IConfigurationSource; Assembly assembly = Assembly.Load("Danel.Nursing.Model"); ActiveRecordStarter.Initialize(assembly, configSource); WindsorContainer windsorContainer = ApplicationUtils.GetWindsorContainer(); windsorContainer.Kernel.AddComponentInstance<ApplicationView>(this); windsorContainer.Kernel.AddComponent(typeof(ApplicationController).Name, typeof(ApplicationController)); controller = windsorContainer.Resolve<ApplicationController>(); // exception is thrown here OnApplicationLoad(args); } The stack trace is this: Castle.MicroKernel.ComponentActivator.ComponentActivatorException was unhandled Message="ComponentActivator: could not instantiate Danel.Nursing.Scheduling.Actions.DataServices.NurseAbsenceDataService" Source="Castle.MicroKernel" StackTrace: at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstance(CreationContext context, Object[] arguments, Type[] signature) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context) at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext context) at Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext context) at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context) at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveServiceDependency(CreationContext context, ComponentModel model, DependencyModel dependency) at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model, DependencyModel dependency) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context, Type[]& signature) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context) at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext context) at Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext context) at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context) at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveServiceDependency(CreationContext context, ComponentModel model, DependencyModel dependency) at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model, DependencyModel dependency) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context, Type[]& signature) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context) at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext context) at Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext context) at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context) at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveServiceDependency(CreationContext context, ComponentModel model, DependencyModel dependency) at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model, DependencyModel dependency) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context, Type[]& signature) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context) at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext context) at Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext context) at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context) at Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, IDictionary additionalArguments) at Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service) at Castle.MicroKernel.DefaultKernel.get_Item(Type service) at Castle.Windsor.WindsorContainer.Resolve(Type service) at Castle.Windsor.WindsorContainer.ResolveT at Danel.Nursing.Scheduling.ApplicationView..ctor(String[] args) in E:\Agile\Scheduling\Danel.Nursing.Scheduling\ApplicationView.cs:line 65 at Danel.Nursing.Scheduling.Program.Main(String[] args) in E:\Agile\Scheduling\Danel.Nursing.Scheduling\Program.cs:line 24 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.ArgumentNullException Message="Value cannot be null.\r\nParameter name: types" Source="mscorlib" ParamName="types" StackTrace: at System.Type.GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.FastCreateInstance(Type implType, Object[] arguments, Type[] signature) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstance(CreationContext context, Object[] arguments, Type[] signature) InnerException: It actually says that the type that I'm trying to initialize does not exist, I think. This is the concreate type that it complains about: namespace Danel.Nursing.Scheduling.Actions.DataServices { using System; using Helpers; using Rhino.Commons; using Danel.Nursing.Model; using NHibernate.Expressions; using System.Collections.Generic; using DateUtil = Danel.Nursing.Scheduling.Actions.Helpers.DateUtil; using Danel.Nursing.Scheduling.Actions.DataServices.Interfaces; public class NurseAbsenceDataService : AbstractDataService<NurseAbsence>, INurseAbsenceDataService { NurseAbsenceDataService(IRepository<NurseAbsence> repository) : base(repository) { } //... } } The AbstractDataService only holds the IRepository for now. Anyone got an idea why the exception is thrown?

    Read the article

1 2  | Next Page >