Lenka Rolinek | 9 May 14:03 2012

RE: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

Hi,

 

I am hoping someone can help…

 

We have a multi assembly ASP.NET MVC 3 application that runs on IIS7.5.

We are using log4net version 1.2.10.

We call log4net LogManager.GetLogger(“loggerName”).Error(“…”); from all assemblies of our web application.

 

Logging from all assemblies works when we run our web application on our development systems from MS Studio 2010.

I.e. the log contains logged information from all our application assemblies.

 

Logging from assemblies but the main one (the one from which log4net was registered, i.e. includes global.asax.cs file) does _NOT_ work when we run our web application installed on IIS7.5.

I.e. the log contains logged information from the application assembly only.

 

 

Following is a list of all log4net ‘configuration parts’ in our application:

 

1.       Log4net configuration is stored in a config file dedicated for log4net. 

The content of this file is below.

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

 

    <configSections>

        <!-- To support configuration file change detection. -->

        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

    </configSections>

 

    <!-- To turn the logging off completely, set threshold to OFF as shown below. -->

    <!-- log4net threshold="OFF" -->

    <log4net>

        <!-- Set root logger level to ERROR or above and its appender to RollingFile. -->

        <!-- Note, loggers that are not listed here will use root logger settings. -->

        <!-- Logger levels are -

        All  DEBUG  INFO  WARN  ERROR  FATAL  OFF

        -->

        <root>

            <level value="ALL" />

            <appender-ref ref="RollingFile" />

        </root>

        <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">

            <file value="logFile.txt" />

            <appendToFile value="true" />

            <staticLogFileName value="true" />

            <rollingStyle value="Size" />

            <maximumFileSize value="10MB" />

            <maxSizeRollBackups value="5" />

            <layout type="log4net.Layout.PatternLayout">

                <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss} %5level %logger: %message%newline" />

            </layout>

                     <!-- example of exclude filter

            <filter type="log4net.Filter.LoggerMatchFilter">

                <loggerToMatch value="TextToMatch" />

                <acceptOnMatch value="false" />

            </filter>

                     -->

        </appender>

    </log4net>

 

</configuration>

 

 

2.       We inititialise the logging in global.asax.cs file using the following API and we are positive the location of the configuration file is correct.

 

      protected void Application_Start()

      {

         try

         {

            // Configure log4net

            string webConfigPath = HttpContext.Current.Server.MapPath("~") + <at> "Web.log4net.config";

            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(webConfigPath));

 

3.       We also give the web application pool privileges to create/write log file in the folder that is meant to contain log files.

 

4.       We also enabled getting HttpContext as suggested on this discussion - http://sgomez.blogspot.com.au/2009/03/log4net-with-wcf-services.html

   [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

   [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

   public class DataView

   {

   …

   }

 

 

Is there anything else we must do?

Is it expected to work with log4net version 1.2.10?

Any suggestions?

 

 

Regards,

Lenka

 


_____________________________________________________________________

This email is intended only for the use of the individual or entity named above and may contain information that is confidential and/or privileged. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this Email is strictly prohibited. If you have received this Email in error, please notify us immediately by return email or telephone +61 2 9966 1066 and destroy the original message. Thank You
_______________________________________________________________________
Todd | 9 May 15:26 2012
Picon

Re: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

Could it be permissions? Remember, when you run locally, you're running under your account. When you run on a remote server, it's typically configured to run under a service account. That account needs to have permission to log. Furthermore, if you're using impersonation, the STARTUP events in global.asax.cs runs under the pool account, but code on the user thread runs under the impersonated account.
 
This can be a pain to debug because l4n silently fails under a situation like this and then disables the appender for the rest of that application's lifetime.

From: Lenka Rolinek <Lenka.Rolinek <at> ir.com>
To: log4net-user <at> logging.apache.org
Sent: Wednesday, May 9, 2012 8:03 AM
Subject: RE: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

<!-- #yiv109859334 _filtered #yiv109859334 {font-family:"Cambria Math";panose-1:2 4 5 3 5 4 6 3 2 4;} _filtered #yiv109859334 {font-family:Calibri;panose-1:2 15 5 2 2 2 4 3 2 4;} _filtered #yiv109859334 {font-family:Consolas;panose-1:2 11 6 9 2 2 4 3 2 4;} #yiv109859334 #yiv109859334 p.yiv109859334MsoNormal, #yiv109859334 li.yiv109859334MsoNormal, #yiv109859334 div.yiv109859334MsoNormal {margin:0in;margin-bottom:.0001pt;font-size:11.0pt;font-family:"sans-serif";} #yiv109859334 a:link, #yiv109859334 span.yiv109859334MsoHyperlink {color:blue;text-decoration:underline;} #yiv109859334 a:visited, #yiv109859334 span.yiv109859334MsoHyperlinkFollowed {color:purple;text-decoration:underline;} #yiv109859334 p.yiv109859334MsoListParagraph, #yiv109859334 li.yiv109859334MsoListParagraph, #yiv109859334 div.yiv109859334MsoListParagraph {margin-top:0in;margin-right:0in;margin-bottom:0in;margin-left:.5in;margin-bottom:.0001pt;font-size:11.0pt;font-family:"sans-serif";} #yiv109859334 span.yiv109859334EmailStyle18 {font-family:"sans-serif";color:windowtext;} #yiv109859334 span.yiv109859334EmailStyle19 {font-family:"sans-serif";color:#1F497D;} #yiv109859334 .yiv109859334MsoChpDefault {font-size:10.0pt;} _filtered #yiv109859334 {margin:1.0in 1.0in 1.0in 1.0in;} #yiv109859334 div.yiv109859334WordSection1 {} #yiv109859334 _filtered #yiv109859334 {} _filtered #yiv109859334 {margin-left:.25in;} _filtered #yiv109859334 {} _filtered #yiv109859334 {} _filtered #yiv109859334 {} _filtered #yiv109859334 {} _filtered #yiv109859334 {} _filtered #yiv109859334 {} _filtered #yiv109859334 {} _filtered #yiv109859334 {} #yiv109859334 ol {margin-bottom:0in;} #yiv109859334 ul {margin-bottom:0in;} -->
Hi,
 
I am hoping someone can help…
 
We have a multi assembly ASP.NET MVC 3 application that runs on IIS7.5.
We are using log4net version 1.2.10.
We call log4net LogManager.GetLogger(“loggerName”).Error(“…”); from all assemblies of our web application.
 
Logging from all assemblies works when we run our web application on our development systems from MS Studio 2010.
I.e. the log contains logged information from all our application assemblies.
 
Logging from assemblies but the main one (the one from which log4net was registered, i.e. includes global.asax.cs file) does _NOT_ work when we run our web application installed on IIS7.5.
I.e. the log contains logged information from the application assembly only.
 
 
Following is a list of all log4net ‘configuration parts’ in our application:
 
1.       Log4net configuration is stored in a config file dedicated for log4net. 
The content of this file is below.
 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 
    <configSections>
        <!-- To support configuration file change detection. -->
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
 
    <!-- To turn the logging off completely, set threshold to OFF as shown below. -->
    <!-- log4net threshold="OFF" -->
    <log4net>
        <!-- Set root logger level to ERROR or above and its appender to RollingFile. -->
        <!-- Note, loggers that are not listed here will use root logger settings. -->
        <!-- Logger levels are -
        All  DEBUG  INFO  WARN  ERROR  FATAL  OFF
        -->
        <root>
            <level value="ALL" />
            <appender-ref ref="RollingFile" />
        </root>
        <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
            <file value="logFile.txt" />
            <appendToFile value="true" />
            <staticLogFileName value="true" />
            <rollingStyle value="Size" />
            <maximumFileSize value="10MB" />
            <maxSizeRollBackups value="5" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss} %5level %logger: %message%newline" />
            </layout>
                     <!-- example of exclude filter
            <filter type="log4net.Filter.LoggerMatchFilter">
                <loggerToMatch value="TextToMatch" />
                <acceptOnMatch value="false" />
            </filter>
                     -->
        </appender>
    </log4net>
 
</configuration>
 
 
2.       We inititialise the logging in global.asax.cs file using the following API and we are positive the location of the configuration file is correct.
 
      protected void Application_Start()
      {
         try
         {
            // Configure log4net
            string webConfigPath = HttpContext.Current.Server.MapPath("~") + <at> "Web.log4net.config";
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(webConfigPath));
 
3.       We also give the web application pool privileges to create/write log file in the folder that is meant to contain log files.
 
4.       We also enabled getting HttpContext as suggested on this discussion - http://sgomez.blogspot.com.au/2009/03/log4net-with-wcf-services.html
   [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
   [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
   public class DataView
   {
   …
   }
 
 
Is there anything else we must do?
Is it expected to work with log4net version 1.2.10?
Any suggestions?
 
 
Regards,
Lenka
 

_____________________________________________________________________

This email is intended only for the use of the individual or entity named above and may contain information that is confidential and/or privileged. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this Email is strictly prohibited. If you have received this Email in error, please notify us immediately by return email or telephone +61 2 9966 1066 and destroy the original message. Thank You
_______________________________________________________________________


Venkatasamy, Vanitha | 9 May 16:07 2012

RE: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

Hi,

  I have implemented the Log4Net for .Net3.5 web application with IIS 7. Ours is multiple environment like windows 2003 iis6 ,windows 2008 iis 7 and windows7 IIS7 like that.

Below are the few suggestions you can try ,

 

1.       Implement the log4net in a separate dll and call it in the Global.asax.cs file like below.

 

    void Application_Start(object sender, EventArgs e)

    {

        // Code that runs on application startup

log4net.Config.XmlConfigurator.Configure();

 }

 

       void Application_Error(object sender, EventArgs e)

       {

 

        // Code that runs when an unhandled error occurs

        string strErrorPage;       

  Exception objErr = Server.GetLastError().GetBaseException();

                   dllname.ErrorLogging logger = new dllname.ErrorLogging();

strErrorPage = logger.logEventError(System.Configuration.ConfigurationManager.AppSettings["Source"].ToString(), System.Configuration.ConfigurationManager.AppSettings["Log"].ToString(),  HttpContext.Current, Request, objErr, strBotPath);

}

 

 

2.       You can have the initialization and error logging in that dll . In the dll app log the error as below

 

    public static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

       public String logEventError(String sourceName, String logName, HttpContext errContext, HttpRequest errRequest, Exception objErr,  string strBotListPath)

        {

               log4net.Config.XmlConfigurator.Configure();

                bool y = LogManager.GetRepository().Configured;

            log4net.ThreadContext.Properties["EventID"] = 5;

                if (objErr.GetType() == typeof(HttpException))

             {

               checkException = (HttpException)objErr;

           }

             if ((log.IsErrorEnabled) && ((checkException.GetHttpCode() == 500) || (checkException.GetHttpCode() == 404)))

               {

        

                

                if(checkException.GetHttpCode() == 500)              

                log4net.ThreadContext.Properties["Category"] = "500";

                else

                log4net.ThreadContext.Properties["Category"] = "404";

 

                log.Error("Error" + sbErrorMessage.ToString() + "Log Name " + logn + "Repository" + logr);

 

           }

     }

 

 

3.       I also encountered few permissions issues like authorization to write to a event viewer, but yours is  a text file so just make sure the folder that contains the .txt file has permission for IUSRS or Network_Service.

 

4.       Try to access the config file as

 

log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.GetDirectoryName(Assembly.GetAssembly(GetType()).Location) + <at> "\" + "xxx.config"));

 

        5.In the web.config file enable the log4net debugging as below ,it might show you the actual error

 

      <add key="log4net.Internal.Debug" value="true" />

      <system.diagnostics>

        <trace autoflush="true">

          <listeners>

          <add name="textWriterTraceListener"

           type="System.Diagnostics.TextWriterTraceListener"

           initializeData="C:\log-file-debug.txt" />

         </listeners>

       </trace>

     </system.diagnostics>

 

Hope it helps u …

 

Thanks,

Vanitha

 

From: Lenka Rolinek [mailto:Lenka.Rolinek <at> ir.com]
Sent: Wednesday, May 09, 2012 8:03 AM
To: log4net-user <at> logging.apache.org
Subject: RE: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

 

Hi,

 

I am hoping someone can help…

 

We have a multi assembly ASP.NET MVC 3 application that runs on IIS7.5.

We are using log4net version 1.2.10.

We call log4net LogManager.GetLogger(“loggerName”).Error(“…”); from all assemblies of our web application.

 

Logging from all assemblies works when we run our web application on our development systems from MS Studio 2010.

I.e. the log contains logged information from all our application assemblies.

 

Logging from assemblies but the main one (the one from which log4net was registered, i.e. includes global.asax.cs file) does _NOT_ work when we run our web application installed on IIS7.5.

I.e. the log contains logged information from the application assembly only.

 

 

Following is a list of all log4net ‘configuration parts’ in our application:

 

1.       Log4net configuration is stored in a config file dedicated for log4net. 

The content of this file is below.

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

 

    <configSections>

        <!-- To support configuration file change detection. -->

        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

    </configSections>

 

    <!-- To turn the logging off completely, set threshold to OFF as shown below. -->

    <!-- log4net threshold="OFF" -->

    <log4net>

        <!-- Set root logger level to ERROR or above and its appender to RollingFile. -->

        <!-- Note, loggers that are not listed here will use root logger settings. -->

        <!-- Logger levels are -

        All  DEBUG  INFO  WARN  ERROR  FATAL  OFF

        -->

        <root>

            <level value="ALL" />

            <appender-ref ref="RollingFile" />

        </root>

        <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">

            <file value="logFile.txt" />

            <appendToFile value="true" />

            <staticLogFileName value="true" />

            <rollingStyle value="Size" />

            <maximumFileSize value="10MB" />

            <maxSizeRollBackups value="5" />

            <layout type="log4net.Layout.PatternLayout">

                <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss} %5level %logger: %message%newline" />

            </layout>

                     <!-- example of exclude filter

            <filter type="log4net.Filter.LoggerMatchFilter">

                <loggerToMatch value="TextToMatch" />

                <acceptOnMatch value="false" />

            </filter>

                     -->

        </appender>

    </log4net>

 

</configuration>

 

 

2.       We inititialise the logging in global.asax.cs file using the following API and we are positive the location of the configuration file is correct.

 

      protected void Application_Start()

      {

         try

         {

            // Configure log4net

            string webConfigPath = HttpContext.Current.Server.MapPath("~") + <at> "Web.log4net.config";

            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(webConfigPath));

 

3.       We also give the web application pool privileges to create/write log file in the folder that is meant to contain log files.

 

4.       We also enabled getting HttpContext as suggested on this discussion - http://sgomez.blogspot.com.au/2009/03/log4net-with-wcf-services.html

   [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

   [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

   public class DataView

   {

   …

   }

 

 

Is there anything else we must do?

Is it expected to work with log4net version 1.2.10?

Any suggestions?

 

 

Regards,

Lenka

 


_____________________________________________________________________

This email is intended only for the use of the individual or entity named above and may contain information that is confidential and/or privileged. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this Email is strictly prohibited. If you have received this Email in error, please notify us immediately by return email or telephone +61 2 9966 1066 and destroy the original message. Thank You
_______________________________________________________________________



This message contains Devin Group confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail.
Please notify the sender immediately by e-mail if you have received this e-mail in error and delete this e-mail from your system. E-mail transmissions cannot be guaranteed secure, error-free and information could be intercepted, corrupted, lost, destroyed, arrive late, incomplete, or contain viruses. The sender therefore does not accept liability for errors or omissions in the contents of this message which may arise as result of transmission. If verification is required please request hard-copy version.
Lenka Rolinek | 11 May 06:29 2012

RE: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

Hi Vanitha,

 

Enabling log4net debugging help me to find the problem.

 

Thank you for your help,

Lenka

 

 

From: Venkatasamy, Vanitha [mailto:Vanitha.Venkatasamy <at> xpandcorp.com]
Sent: 10. května 2012 0:08
To: Log4NET User
Subject: RE: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

 

Hi,

  I have implemented the Log4Net for .Net3.5 web application with IIS 7. Ours is multiple environment like windows 2003 iis6 ,windows 2008 iis 7 and windows7 IIS7 like that.

Below are the few suggestions you can try ,

 

1.       Implement the log4net in a separate dll and call it in the Global.asax.cs file like below.

 

    void Application_Start(object sender, EventArgs e)

    {

        // Code that runs on application startup

log4net.Config.XmlConfigurator.Configure();

 }

 

       void Application_Error(object sender, EventArgs e)

       {

 

        // Code that runs when an unhandled error occurs

        string strErrorPage;       

  Exception objErr = Server.GetLastError().GetBaseException();

                   dllname.ErrorLogging logger = new dllname.ErrorLogging();

strErrorPage = logger.logEventError(System.Configuration.ConfigurationManager.AppSettings["Source"].ToString(), System.Configuration.ConfigurationManager.AppSettings["Log"].ToString(),  HttpContext.Current, Request, objErr, strBotPath);

}

 

 

2.       You can have the initialization and error logging in that dll . In the dll app log the error as below

 

    public static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

       public String logEventError(String sourceName, String logName, HttpContext errContext, HttpRequest errRequest, Exception objErr,  string strBotListPath)

        {

               log4net.Config.XmlConfigurator.Configure();

                bool y = LogManager.GetRepository().Configured;

            log4net.ThreadContext.Properties["EventID"] = 5;

                if (objErr.GetType() == typeof(HttpException))

             {

               checkException = (HttpException)objErr;

           }

             if ((log.IsErrorEnabled) && ((checkException.GetHttpCode() == 500) || (checkException.GetHttpCode() == 404)))

               {

        

                

                if(checkException.GetHttpCode() == 500)              

                log4net.ThreadContext.Properties["Category"] = "500";

                else

                log4net.ThreadContext.Properties["Category"] = "404";

 

                log.Error("Error" + sbErrorMessage.ToString() + "Log Name " + logn + "Repository" + logr);

 

           }

     }

 

 

3.       I also encountered few permissions issues like authorization to write to a event viewer, but yours is  a text file so just make sure the folder that contains the .txt file has permission for IUSRS or Network_Service.

 

4.       Try to access the config file as

 

log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.GetDirectoryName(Assembly.GetAssembly(GetType()).Location) + <at> "\" + "xxx.config"));

 

        5.In the web.config file enable the log4net debugging as below ,it might show you the actual error

 

      <add key="log4net.Internal.Debug" value="true" />

      <system.diagnostics>

        <trace autoflush="true">

          <listeners>

          <add name="textWriterTraceListener"

           type="System.Diagnostics.TextWriterTraceListener"

           initializeData="C:\log-file-debug.txt" />

         </listeners>

       </trace>

     </system.diagnostics>

 

Hope it helps u …

 

Thanks,

Vanitha

 

From: Lenka Rolinek [mailto:Lenka.Rolinek <at> ir.com]
Sent: Wednesday, May 09, 2012 8:03 AM
To: log4net-user <at> logging.apache.org
Subject: RE: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

 

Hi,

 

I am hoping someone can help…

 

We have a multi assembly ASP.NET MVC 3 application that runs on IIS7.5.

We are using log4net version 1.2.10.

We call log4net LogManager.GetLogger(“loggerName”).Error(“…”); from all assemblies of our web application.

 

Logging from all assemblies works when we run our web application on our development systems from MS Studio 2010.

I.e. the log contains logged information from all our application assemblies.

 

Logging from assemblies but the main one (the one from which log4net was registered, i.e. includes global.asax.cs file) does _NOT_ work when we run our web application installed on IIS7.5.

I.e. the log contains logged information from the application assembly only.

 

 

Following is a list of all log4net ‘configuration parts’ in our application:

 

1.       Log4net configuration is stored in a config file dedicated for log4net. 

The content of this file is below.

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

 

    <configSections>

        <!-- To support configuration file change detection. -->

        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

    </configSections>

 

    <!-- To turn the logging off completely, set threshold to OFF as shown below. -->

    <!-- log4net threshold="OFF" -->

    <log4net>

        <!-- Set root logger level to ERROR or above and its appender to RollingFile. -->

        <!-- Note, loggers that are not listed here will use root logger settings. -->

        <!-- Logger levels are -

        All  DEBUG  INFO  WARN  ERROR  FATAL  OFF

        -->

        <root>

            <level value="ALL" />

            <appender-ref ref="RollingFile" />

        </root>

        <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">

            <file value="logFile.txt" />

            <appendToFile value="true" />

            <staticLogFileName value="true" />

            <rollingStyle value="Size" />

            <maximumFileSize value="10MB" />

            <maxSizeRollBackups value="5" />

            <layout type="log4net.Layout.PatternLayout">

                <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss} %5level %logger: %message%newline" />

            </layout>

                     <!-- example of exclude filter

            <filter type="log4net.Filter.LoggerMatchFilter">

                <loggerToMatch value="TextToMatch" />

                <acceptOnMatch value="false" />

            </filter>

                     -->

        </appender>

    </log4net>

 

</configuration>

 

 

2.       We inititialise the logging in global.asax.cs file using the following API and we are positive the location of the configuration file is correct.

 

      protected void Application_Start()

      {

         try

         {

            // Configure log4net

            string webConfigPath = HttpContext.Current.Server.MapPath("~") + <at> "Web.log4net.config";

            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(webConfigPath));

 

3.       We also give the web application pool privileges to create/write log file in the folder that is meant to contain log files.

 

4.       We also enabled getting HttpContext as suggested on this discussion - http://sgomez.blogspot.com.au/2009/03/log4net-with-wcf-services.html

   [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

   [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

   public class DataView

   {

   …

   }

 

 

Is there anything else we must do?

Is it expected to work with log4net version 1.2.10?

Any suggestions?

 

 

Regards,

Lenka

 


_____________________________________________________________________

This email is intended only for the use of the individual or entity named above and may contain information that is confidential and/or privileged. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this Email is strictly prohibited. If you have received this Email in error, please notify us immediately by return email or telephone +61 2 9966 1066 and destroy the original message. Thank You
_______________________________________________________________________

 


This message contains Devin Group confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail.
Please notify the sender immediately by e-mail if you have received this e-mail in error and delete this e-mail from your system. E-mail transmissions cannot be guaranteed secure, error-free and information could be intercepted, corrupted, lost, destroyed, arrive late, incomplete, or contain viruses. The sender therefore does not accept liability for errors or omissions in the contents of this message which may arise as result of transmission. If verification is required please request hard-copy version.

_____________________________________________________________________
This e-mail has been scanned for viruses by MCI's Internet Managed
Scanning Services - powered by MessageLabs. For further information
visit http://www.mci.com


_____________________________________________________________________

This email is intended only for the use of the individual or entity named above and may contain information that is confidential and/or privileged. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this Email is strictly prohibited. If you have received this Email in error, please notify us immediately by return email or telephone +61 2 9966 1066 and destroy the original message. Thank You
_______________________________________________________________________
Venkatasamy, Vanitha | 11 May 15:09 2012

RE: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

I am glad it helped you…

 

From: Lenka Rolinek [mailto:Lenka.Rolinek <at> ir.com]
Sent: Friday, May 11, 2012 12:30 AM
To: Log4NET User
Subject: RE: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

 

Hi Vanitha,

 

Enabling log4net debugging help me to find the problem.

 

Thank you for your help,

Lenka

 

 

From: Venkatasamy, Vanitha [mailto:Vanitha.Venkatasamy <at> xpandcorp.com]
Sent: 10. května 2012 0:08
To: Log4NET User
Subject: RE: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

 

Hi,

  I have implemented the Log4Net for .Net3.5 web application with IIS 7. Ours is multiple environment like windows 2003 iis6 ,windows 2008 iis 7 and windows7 IIS7 like that.

Below are the few suggestions you can try ,

 

1.       Implement the log4net in a separate dll and call it in the Global.asax.cs file like below.

 

    void Application_Start(object sender, EventArgs e)

    {

        // Code that runs on application startup

log4net.Config.XmlConfigurator.Configure();

 }

 

       void Application_Error(object sender, EventArgs e)

       {

 

        // Code that runs when an unhandled error occurs

        string strErrorPage;       

  Exception objErr = Server.GetLastError().GetBaseException();

                   dllname.ErrorLogging logger = new dllname.ErrorLogging();

strErrorPage = logger.logEventError(System.Configuration.ConfigurationManager.AppSettings["Source"].ToString(), System.Configuration.ConfigurationManager.AppSettings["Log"].ToString(),  HttpContext.Current, Request, objErr, strBotPath);

}

 

 

2.       You can have the initialization and error logging in that dll . In the dll app log the error as below

 

    public static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

       public String logEventError(String sourceName, String logName, HttpContext errContext, HttpRequest errRequest, Exception objErr,  string strBotListPath)

        {

               log4net.Config.XmlConfigurator.Configure();

                bool y = LogManager.GetRepository().Configured;

            log4net.ThreadContext.Properties["EventID"] = 5;

                if (objErr.GetType() == typeof(HttpException))

             {

               checkException = (HttpException)objErr;

           }

             if ((log.IsErrorEnabled) && ((checkException.GetHttpCode() == 500) || (checkException.GetHttpCode() == 404)))

               {

        

                

                if(checkException.GetHttpCode() == 500)              

                log4net.ThreadContext.Properties["Category"] = "500";

                else

                log4net.ThreadContext.Properties["Category"] = "404";

 

                log.Error("Error" + sbErrorMessage.ToString() + "Log Name " + logn + "Repository" + logr);

 

           }

     }

 

 

3.       I also encountered few permissions issues like authorization to write to a event viewer, but yours is  a text file so just make sure the folder that contains the .txt file has permission for IUSRS or Network_Service.

 

4.       Try to access the config file as

 

log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.GetDirectoryName(Assembly.GetAssembly(GetType()).Location) + <at> "\" + "xxx.config"));

 

        5.In the web.config file enable the log4net debugging as below ,it might show you the actual error

 

      <add key="log4net.Internal.Debug" value="true" />

      <system.diagnostics>

        <trace autoflush="true">

          <listeners>

          <add name="textWriterTraceListener"

           type="System.Diagnostics.TextWriterTraceListener"

           initializeData="C:\log-file-debug.txt" />

         </listeners>

       </trace>

     </system.diagnostics>

 

Hope it helps u …

 

Thanks,

Vanitha

 

From: Lenka Rolinek [mailto:Lenka.Rolinek <at> ir.com]
Sent: Wednesday, May 09, 2012 8:03 AM
To: log4net-user <at> logging.apache.org
Subject: RE: log4net usage in IIS7.5 ASP.NET MVC (multi assembly) application

 

Hi,

 

I am hoping someone can help…

 

We have a multi assembly ASP.NET MVC 3 application that runs on IIS7.5.

We are using log4net version 1.2.10.

We call log4net LogManager.GetLogger(“loggerName”).Error(“…”); from all assemblies of our web application.

 

Logging from all assemblies works when we run our web application on our development systems from MS Studio 2010.

I.e. the log contains logged information from all our application assemblies.

 

Logging from assemblies but the main one (the one from which log4net was registered, i.e. includes global.asax.cs file) does _NOT_ work when we run our web application installed on IIS7.5.

I.e. the log contains logged information from the application assembly only.

 

 

Following is a list of all log4net ‘configuration parts’ in our application:

 

1.       Log4net configuration is stored in a config file dedicated for log4net. 

The content of this file is below.

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

 

    <configSections>

        <!-- To support configuration file change detection. -->

        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

    </configSections>

 

    <!-- To turn the logging off completely, set threshold to OFF as shown below. -->

    <!-- log4net threshold="OFF" -->

    <log4net>

        <!-- Set root logger level to ERROR or above and its appender to RollingFile. -->

        <!-- Note, loggers that are not listed here will use root logger settings. -->

        <!-- Logger levels are -

        All  DEBUG  INFO  WARN  ERROR  FATAL  OFF

        -->

        <root>

            <level value="ALL" />

            <appender-ref ref="RollingFile" />

        </root>

        <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">

            <file value="logFile.txt" />

            <appendToFile value="true" />

            <staticLogFileName value="true" />

            <rollingStyle value="Size" />

            <maximumFileSize value="10MB" />

            <maxSizeRollBackups value="5" />

            <layout type="log4net.Layout.PatternLayout">

                <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss} %5level %logger: %message%newline" />

            </layout>

                     <!-- example of exclude filter

            <filter type="log4net.Filter.LoggerMatchFilter">

                <loggerToMatch value="TextToMatch" />

                <acceptOnMatch value="false" />

            </filter>

                     -->

        </appender>

    </log4net>

 

</configuration>

 

 

2.       We inititialise the logging in global.asax.cs file using the following API and we are positive the location of the configuration file is correct.

 

      protected void Application_Start()

      {

         try

         {

            // Configure log4net

            string webConfigPath = HttpContext.Current.Server.MapPath("~") + <at> "Web.log4net.config";

            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(webConfigPath));

 

3.       We also give the web application pool privileges to create/write log file in the folder that is meant to contain log files.

 

4.       We also enabled getting HttpContext as suggested on this discussion - http://sgomez.blogspot.com.au/2009/03/log4net-with-wcf-services.html

   [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

   [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

   public class DataView

   {

   …

   }

 

 

Is there anything else we must do?

Is it expected to work with log4net version 1.2.10?

Any suggestions?

 

 

Regards,

Lenka

 


_____________________________________________________________________

This email is intended only for the use of the individual or entity named above and may contain information that is confidential and/or privileged. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this Email is strictly prohibited. If you have received this Email in error, please notify us immediately by return email or telephone +61 2 9966 1066 and destroy the original message. Thank You
_______________________________________________________________________

 


This message contains Devin Group confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail.
Please notify the sender immediately by e-mail if you have received this e-mail in error and delete this e-mail from your system. E-mail transmissions cannot be guaranteed secure, error-free and information could be intercepted, corrupted, lost, destroyed, arrive late, incomplete, or contain viruses. The sender therefore does not accept liability for errors or omissions in the contents of this message which may arise as result of transmission. If verification is required please request hard-copy version.

_____________________________________________________________________
This e-mail has been scanned for viruses by MCI's Internet Managed
Scanning Services - powered by MessageLabs. For further information
visit http://www.mci.com


_____________________________________________________________________

This email is intended only for the use of the individual or entity named above and may contain information that is confidential and/or privileged. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this Email is strictly prohibited. If you have received this Email in error, please notify us immediately by return email or telephone +61 2 9966 1066 and destroy the original message. Thank You
_______________________________________________________________________



This message contains Devin Group confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail.
Please notify the sender immediately by e-mail if you have received this e-mail in error and delete this e-mail from your system. E-mail transmissions cannot be guaranteed secure, error-free and information could be intercepted, corrupted, lost, destroyed, arrive late, incomplete, or contain viruses. The sender therefore does not accept liability for errors or omissions in the contents of this message which may arise as result of transmission. If verification is required please request hard-copy version.
Michele Lepri | 13 May 20:52 2012
Picon

Re: Logger not working in an ASP.Net environment only works with full trust

Hello all,
I fall into the same problem: unluckily the advices of Vanitha
Venkatasamy in the other reply don't solve the issue.

Adding this attribute
[assembly:
System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]

like written here:
http://stackoverflow.com/questions/2279896/log4net-and-net-4-0-rc

change only the exception in:

*****
Description: The application attempted to perform an operation not
allowed by the security policy.  To grant this application the required
permission please contact your system administrator or change the
application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the
permission of type 'System.Security.Permissions.FileIOPermission,
mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' failed.
*****

Of course I can't change the security policy.

The author of the reply say it is related to how Log4Net is written.

Any idea?
I have to open a jira issue for this?

thanks
michele

Il 14/03/2012 19:09, Dennis Minderhoud ha scritto:
> I've made a simple .NET 4 Web Application in VS2010, and added a
> reference to log4net 1.2.11.0 (latest).
> 
> In this project I've made a |Logger| class:
> public static class Logger
> {
>     private static readonly log4net.ILog log;
> 
>     static Logger()
>     {
>         try {
>             log4net.Config.XmlConfigurator.Configure();
>             log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); 
> 
>         }
>         catch (Exception e)
>         {
>             System.Diagnostics.Debug.Write(e.ToString());
>         }
>     }
> 
>     public static void LogInfo(string information)
>     {
>         log.Info(information);
>     }
> 
>     public static void LogError(string erroMessage, Exception ex)
>     {
>         log.Error(erroMessage, ex);
>     }
> 
>     public static void LogWarnings(string warningText)
>     {
>         log.Warn(warningText);
>     }
> 
>     public static void Fatal(string fatalText)
>     {
>         log.Fatal(fatalText);
>     }
> }
> 
> When I call this |Logger|class (|Logger.Fatal("Test");|) in a Full trust
> environment, everything works correct. However, when I change the trust
> level to High (or Medium) it fails with the following exception:
> 
> System.Reflection.TargetInvocationException: Exception has been thrown
> by the target of an invocation. ---> System.TypeLoadException:
> Inheritance security rules violated while overriding member:
> 'log4net.Util.ReadOnlyPropertiesDictionary.GetObjectData(System.Runtime.Serialization.SerializationInfo,
> System.Runtime.Serialization.StreamingContext)'. Security accessibility
> of the overriding method must match the security accessibility of the
> method being overriden.
>    at log4net.Repository.Hierarchy.Hierarchy..ctor(ILoggerFactory
> loggerFactory)
>    at log4net.Repository.Hierarchy.Hierarchy..ctor()
>    --- End of inner exception stack trace ---
>    at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean
> publicOnly, Boolean noCheck, Boolean& canBeCached,
> RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
>    at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
> skipCheckThis, Boolean fillCache)
>    at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
> Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
>    at System.Activator.CreateInstance(Type type, Boolean nonPublic)
>    at log4net.Core.DefaultRepositorySelector.CreateRepository(String
> repositoryName, Type repositoryType)
>    at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly
> repositoryAssembly, Type repositoryType, String repositoryName, Boolean
> readAssemblyAttributes)
>    at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly
> repositoryAssembly, Type repositoryType)
>    at log4net.Core.DefaultRepositorySelector.GetRepository(Assembly
> repositoryAssembly)
>    at log4net.Core.LoggerManager.GetRepository(Assembly repositoryAssembly)
>    at log4net.Config.XmlConfigurator.Configure()
>    at UtilClasses.Logger..cctor() in c:\users\***\documents\visual
> studio 2010\Projects\TestLogging\TestLogging\Default.aspx.cs:line 35
> 
> When I include the log4net project to the solution, I get the exception
> when creating an instance of the default LogRepository:
> 
> rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); on
> line 412of DefaultRepositorySelector.cs
> 
> this is my web.config:
> 
> <?xml version="1.0"?>
> 
> <configuration>
> 
>   <configSections>
>     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
>   </configSections>
>   <system.web>
>     <compilation debug="true" targetFramework="4.0" />
>     <trust level="High" />
>   </system.web>
>   <log4net debug="true">
>     <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
>       <file value="logfile.txt" />
>       <appendToFile value="true" />
>       <rollingStyle value="Date" />
>       <datePattern value="yyyy-MM-dd" />
>       <layout type="log4net.Layout.PatternLayout">
>         <conversionPattern value="%date{dd-MM-yyyy HH:mm:ss,fff} [%-2p] - %C.%M - %m%n" />
>       </layout>
> 
>     </appender>
> 
>     <root>
>       <level value="ALL" />
>       <appender-ref ref="RollingFileAppender" />
>     </root>
>   </log4net>
>   <system.webServer>
>      <modules runAllManagedModulesForAllRequests="true"/>
>   </system.webServer>
> </configuration>
> 
> Other people suggest to add requirePermission=”false”to the section, but
> then the debugger won’t attach to the application pool.
> 
> I hope someone can help me out of this problem.
> 
> Regards,
> 
> Dennis Minderhoud
> 
>  
> 

--

-- 
http://michelelepri.blogspot.com/

Martin Milan | 14 May 10:18 2012

RE: Logger not working in an ASP.Net environment only works with full trust

Whilst you might not be able to change the security policy, perhaps you could get around the problem by
moving whatever is being written into a different folder that would not fall afoul of it?

Martin.


-----Original Message-----
From: Michele Lepri [mailto:michele.lepri <at> gmail.com] 
Sent: 13 May 2012 19:52
To: Log4NET User
Subject: Re: Logger not working in an ASP.Net environment only works with full trust

Hello all,
I fall into the same problem: unluckily the advices of Vanitha Venkatasamy in the other reply don't solve
the issue.

Adding this attribute
[assembly:
System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]

like written here:
http://stackoverflow.com/questions/2279896/log4net-and-net-4-0-rc


change only the exception in:

*****
Description: The application attempted to perform an operation not allowed by the security policy.  To
grant this application the required permission please contact your system administrator or change the
application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission,
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
*****

Of course I can't change the security policy.

The author of the reply say it is related to how Log4Net is written.

Any idea?
I have to open a jira issue for this?

thanks
michele


Il 14/03/2012 19:09, Dennis Minderhoud ha scritto:
> I've made a simple .NET 4 Web Application in VS2010, and added a 
> reference to log4net 1.2.11.0 (latest).
> 
> In this project I've made a |Logger| class:
> public static class Logger
> {
>     private static readonly log4net.ILog log;
> 
>     static Logger()
>     {
>         try {
>             log4net.Config.XmlConfigurator.Configure();
>             log = 
> log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMe
> thod().DeclaringType);
> 
>         }
>         catch (Exception e)
>         {
>             System.Diagnostics.Debug.Write(e.ToString());
>         }
>     }
> 
>     public static void LogInfo(string information)
>     {
>         log.Info(information);
>     }
> 
>     public static void LogError(string erroMessage, Exception ex)
>     {
>         log.Error(erroMessage, ex);
>     }
> 
>     public static void LogWarnings(string warningText)
>     {
>         log.Warn(warningText);
>     }
> 
>     public static void Fatal(string fatalText)
>     {
>         log.Fatal(fatalText);
>     }
> }
> 
> When I call this |Logger|class (|Logger.Fatal("Test");|) in a Full 
> trust environment, everything works correct. However, when I change 
> the trust level to High (or Medium) it fails with the following exception:
> 
> System.Reflection.TargetInvocationException: Exception has been thrown 
> by the target of an invocation. ---> System.TypeLoadException:
> Inheritance security rules violated while overriding member:
> 'log4net.Util.ReadOnlyPropertiesDictionary.GetObjectData(System.Runtim
> e.Serialization.SerializationInfo,
> System.Runtime.Serialization.StreamingContext)'. Security 
> accessibility of the overriding method must match the security 
> accessibility of the method being overriden.
>    at log4net.Repository.Hierarchy.Hierarchy..ctor(ILoggerFactory
> loggerFactory)
>    at log4net.Repository.Hierarchy.Hierarchy..ctor()
>    --- End of inner exception stack trace ---
>    at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, 
> Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, 
> RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
>    at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, 
> Boolean skipCheckThis, Boolean fillCache)
>    at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, 
> Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
>    at System.Activator.CreateInstance(Type type, Boolean nonPublic)
>    at log4net.Core.DefaultRepositorySelector.CreateRepository(String
> repositoryName, Type repositoryType)
>    at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly
> repositoryAssembly, Type repositoryType, String repositoryName, 
> Boolean
> readAssemblyAttributes)
>    at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly
> repositoryAssembly, Type repositoryType)
>    at log4net.Core.DefaultRepositorySelector.GetRepository(Assembly
> repositoryAssembly)
>    at log4net.Core.LoggerManager.GetRepository(Assembly repositoryAssembly)
>    at log4net.Config.XmlConfigurator.Configure()
>    at UtilClasses.Logger..cctor() in c:\users\***\documents\visual 
> studio 2010\Projects\TestLogging\TestLogging\Default.aspx.cs:line 35
> 
> When I include the log4net project to the solution, I get the 
> exception when creating an instance of the default LogRepository:
> 
> rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); on 
> line 412of DefaultRepositorySelector.cs
> 
> this is my web.config:
> 
> <?xml version="1.0"?>
> 
> <configuration>
> 
>   <configSections>
>     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
>   </configSections>
>   <system.web>
>     <compilation debug="true" targetFramework="4.0" />
>     <trust level="High" />
>   </system.web>
>   <log4net debug="true">
>     <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
>       <file value="logfile.txt" />
>       <appendToFile value="true" />
>       <rollingStyle value="Date" />
>       <datePattern value="yyyy-MM-dd" />
>       <layout type="log4net.Layout.PatternLayout">
>         <conversionPattern value="%date{dd-MM-yyyy HH:mm:ss,fff} [%-2p] - %C.%M - %m%n" />
>       </layout>
> 
>     </appender>
> 
>     <root>
>       <level value="ALL" />
>       <appender-ref ref="RollingFileAppender" />
>     </root>
>   </log4net>
>   <system.webServer>
>      <modules runAllManagedModulesForAllRequests="true"/>
>   </system.webServer>
> </configuration>
> 
> Other people suggest to add requirePermission=”false”to the section, 
> but then the debugger won’t attach to the application pool.
> 
> I hope someone can help me out of this problem.
> 
> Regards,
> 
> Dennis Minderhoud
> 
>  
> 


--
http://michelelepri.blogspot.com/


EnServe Group
Michele Lepri | 14 May 11:05 2012
Picon

Re: Logger not working in an ASP.Net environment only works with full trust

Thanks Martin for the reply,
no I can't change the security policy cause this project must run in a
shared hosting.

I think I don't understand what I should move: the folder where I write
the log already have all the needed right, but I think what throw the
security exception is something related to this:

http://msdn.microsoft.com/en-us/library/dd233102%28VS.100%29.aspx

I will investigate deeper I can today later..

michele

Il 14/05/2012 10:18, Martin Milan ha scritto:
> Whilst you might not be able to change the security policy, perhaps you could get around the problem by
moving whatever is being written into a different folder that would not fall afoul of it?
> 
> Martin.
> 
> 
> -----Original Message-----
> From: Michele Lepri [mailto:michele.lepri <at> gmail.com] 
> Sent: 13 May 2012 19:52
> To: Log4NET User
> Subject: Re: Logger not working in an ASP.Net environment only works with full trust
> 
> Hello all,
> I fall into the same problem: unluckily the advices of Vanitha Venkatasamy in the other reply don't solve
the issue.
> 
> Adding this attribute
> [assembly:
> System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]
> 
> like written here:
> http://stackoverflow.com/questions/2279896/log4net-and-net-4-0-rc
> 
> change only the exception in:
> 
> *****
> Description: The application attempted to perform an operation not allowed by the security policy.  To
grant this application the required permission please contact your system administrator or change the
application's trust level in the configuration file.
> 
> Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission,
> mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
> *****
> 
> Of course I can't change the security policy.
> 
> The author of the reply say it is related to how Log4Net is written.
> 
> Any idea?
> I have to open a jira issue for this?
> 
> thanks
> michele
> 
> 
> Il 14/03/2012 19:09, Dennis Minderhoud ha scritto:
>> I've made a simple .NET 4 Web Application in VS2010, and added a 
>> reference to log4net 1.2.11.0 (latest).
>>
>> In this project I've made a |Logger| class:
>> public static class Logger
>> {
>>     private static readonly log4net.ILog log;
>>
>>     static Logger()
>>     {
>>         try {
>>             log4net.Config.XmlConfigurator.Configure();
>>             log = 
>> log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMe
>> thod().DeclaringType);
>>
>>         }
>>         catch (Exception e)
>>         {
>>             System.Diagnostics.Debug.Write(e.ToString());
>>         }
>>     }
>>
>>     public static void LogInfo(string information)
>>     {
>>         log.Info(information);
>>     }
>>
>>     public static void LogError(string erroMessage, Exception ex)
>>     {
>>         log.Error(erroMessage, ex);
>>     }
>>
>>     public static void LogWarnings(string warningText)
>>     {
>>         log.Warn(warningText);
>>     }
>>
>>     public static void Fatal(string fatalText)
>>     {
>>         log.Fatal(fatalText);
>>     }
>> }
>>
>> When I call this |Logger|class (|Logger.Fatal("Test");|) in a Full 
>> trust environment, everything works correct. However, when I change 
>> the trust level to High (or Medium) it fails with the following exception:
>>
>> System.Reflection.TargetInvocationException: Exception has been thrown 
>> by the target of an invocation. ---> System.TypeLoadException:
>> Inheritance security rules violated while overriding member:
>> 'log4net.Util.ReadOnlyPropertiesDictionary.GetObjectData(System.Runtim
>> e.Serialization.SerializationInfo,
>> System.Runtime.Serialization.StreamingContext)'. Security 
>> accessibility of the overriding method must match the security 
>> accessibility of the method being overriden.
>>    at log4net.Repository.Hierarchy.Hierarchy..ctor(ILoggerFactory
>> loggerFactory)
>>    at log4net.Repository.Hierarchy.Hierarchy..ctor()
>>    --- End of inner exception stack trace ---
>>    at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, 
>> Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, 
>> RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
>>    at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, 
>> Boolean skipCheckThis, Boolean fillCache)
>>    at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, 
>> Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
>>    at System.Activator.CreateInstance(Type type, Boolean nonPublic)
>>    at log4net.Core.DefaultRepositorySelector.CreateRepository(String
>> repositoryName, Type repositoryType)
>>    at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly
>> repositoryAssembly, Type repositoryType, String repositoryName, 
>> Boolean
>> readAssemblyAttributes)
>>    at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly
>> repositoryAssembly, Type repositoryType)
>>    at log4net.Core.DefaultRepositorySelector.GetRepository(Assembly
>> repositoryAssembly)
>>    at log4net.Core.LoggerManager.GetRepository(Assembly repositoryAssembly)
>>    at log4net.Config.XmlConfigurator.Configure()
>>    at UtilClasses.Logger..cctor() in c:\users\***\documents\visual 
>> studio 2010\Projects\TestLogging\TestLogging\Default.aspx.cs:line 35
>>
>> When I include the log4net project to the solution, I get the 
>> exception when creating an instance of the default LogRepository:
>>
>> rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); on 
>> line 412of DefaultRepositorySelector.cs
>>
>> this is my web.config:
>>
>> <?xml version="1.0"?>
>>
>> <configuration>
>>
>>   <configSections>
>>     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
>>   </configSections>
>>   <system.web>
>>     <compilation debug="true" targetFramework="4.0" />
>>     <trust level="High" />
>>   </system.web>
>>   <log4net debug="true">
>>     <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
>>       <file value="logfile.txt" />
>>       <appendToFile value="true" />
>>       <rollingStyle value="Date" />
>>       <datePattern value="yyyy-MM-dd" />
>>       <layout type="log4net.Layout.PatternLayout">
>>         <conversionPattern value="%date{dd-MM-yyyy HH:mm:ss,fff} [%-2p] - %C.%M - %m%n" />
>>       </layout>
>>
>>     </appender>
>>
>>     <root>
>>       <level value="ALL" />
>>       <appender-ref ref="RollingFileAppender" />
>>     </root>
>>   </log4net>
>>   <system.webServer>
>>      <modules runAllManagedModulesForAllRequests="true"/>
>>   </system.webServer>
>> </configuration>
>>
>> Other people suggest to add requirePermission=”false”to the section, 
>> but then the debugger won’t attach to the application pool.
>>
>> I hope someone can help me out of this problem.
>>
>> Regards,
>>
>> Dennis Minderhoud
>>
>>  
>>
> 
> 
> --
> http://michelelepri.blogspot.com/
> 
> EnServe Group

--

-- 
http://michelelepri.blogspot.com/

Michele Lepri | 14 May 20:35 2012
Picon

Re: [problem founded] Logger not working in an ASP.Net environment only works with full trust

I think I found what .net 4 policy doesn't like..

According to this:
http://msdn.microsoft.com/en-us/library/bb924412.aspx

Serialization in a partially-truste application should be done in
another way ([DataContract] attribute must used, you can't use
[Serializable] attribute and can't use ISerializable interface to
control the serialization process.

After removed the [Serializable] and the ISerializable interface all
work fine, but of course i "loose" all the code performed by the
implementation of the ISerializable interface.
By the way the log is fine for me now and all I need seem to work.

I thinks this need a look from some log4net dev-team guy, because now
log4net is really unusable in a partially trusted environment.

What do you think?
Should I write in dev-list about it?

Thanks and best regards
michele

Il 14/05/2012 10:18, Martin Milan ha scritto:
> Whilst you might not be able to change the security policy, perhaps you could get around the problem by
moving whatever is being written into a different folder that would not fall afoul of it?
> 
> Martin.
> 
> 
> -----Original Message-----
> From: Michele Lepri [mailto:michele.lepri <at> gmail.com] 
> Sent: 13 May 2012 19:52
> To: Log4NET User
> Subject: Re: Logger not working in an ASP.Net environment only works with full trust
> 
> Hello all,
> I fall into the same problem: unluckily the advices of Vanitha Venkatasamy in the other reply don't solve
the issue.
> 
> Adding this attribute
> [assembly:
> System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]
> 
> like written here:
> http://stackoverflow.com/questions/2279896/log4net-and-net-4-0-rc
> 
> change only the exception in:
> 
> *****
> Description: The application attempted to perform an operation not allowed by the security policy.  To
grant this application the required permission please contact your system administrator or change the
application's trust level in the configuration file.
> 
> Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission,
> mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
> *****
> 
> Of course I can't change the security policy.
> 
> The author of the reply say it is related to how Log4Net is written.
> 
> Any idea?
> I have to open a jira issue for this?
> 
> thanks
> michele
> 
> 
> Il 14/03/2012 19:09, Dennis Minderhoud ha scritto:
>> I've made a simple .NET 4 Web Application in VS2010, and added a 
>> reference to log4net 1.2.11.0 (latest).
>>
>> In this project I've made a |Logger| class:
>> public static class Logger
>> {
>>     private static readonly log4net.ILog log;
>>
>>     static Logger()
>>     {
>>         try {
>>             log4net.Config.XmlConfigurator.Configure();
>>             log = 
>> log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMe
>> thod().DeclaringType);
>>
>>         }
>>         catch (Exception e)
>>         {
>>             System.Diagnostics.Debug.Write(e.ToString());
>>         }
>>     }
>>
>>     public static void LogInfo(string information)
>>     {
>>         log.Info(information);
>>     }
>>
>>     public static void LogError(string erroMessage, Exception ex)
>>     {
>>         log.Error(erroMessage, ex);
>>     }
>>
>>     public static void LogWarnings(string warningText)
>>     {
>>         log.Warn(warningText);
>>     }
>>
>>     public static void Fatal(string fatalText)
>>     {
>>         log.Fatal(fatalText);
>>     }
>> }
>>
>> When I call this |Logger|class (|Logger.Fatal("Test");|) in a Full 
>> trust environment, everything works correct. However, when I change 
>> the trust level to High (or Medium) it fails with the following exception:
>>
>> System.Reflection.TargetInvocationException: Exception has been thrown 
>> by the target of an invocation. ---> System.TypeLoadException:
>> Inheritance security rules violated while overriding member:
>> 'log4net.Util.ReadOnlyPropertiesDictionary.GetObjectData(System.Runtim
>> e.Serialization.SerializationInfo,
>> System.Runtime.Serialization.StreamingContext)'. Security 
>> accessibility of the overriding method must match the security 
>> accessibility of the method being overriden.
>>    at log4net.Repository.Hierarchy.Hierarchy..ctor(ILoggerFactory
>> loggerFactory)
>>    at log4net.Repository.Hierarchy.Hierarchy..ctor()
>>    --- End of inner exception stack trace ---
>>    at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, 
>> Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, 
>> RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
>>    at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, 
>> Boolean skipCheckThis, Boolean fillCache)
>>    at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, 
>> Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
>>    at System.Activator.CreateInstance(Type type, Boolean nonPublic)
>>    at log4net.Core.DefaultRepositorySelector.CreateRepository(String
>> repositoryName, Type repositoryType)
>>    at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly
>> repositoryAssembly, Type repositoryType, String repositoryName, 
>> Boolean
>> readAssemblyAttributes)
>>    at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly
>> repositoryAssembly, Type repositoryType)
>>    at log4net.Core.DefaultRepositorySelector.GetRepository(Assembly
>> repositoryAssembly)
>>    at log4net.Core.LoggerManager.GetRepository(Assembly repositoryAssembly)
>>    at log4net.Config.XmlConfigurator.Configure()
>>    at UtilClasses.Logger..cctor() in c:\users\***\documents\visual 
>> studio 2010\Projects\TestLogging\TestLogging\Default.aspx.cs:line 35
>>
>> When I include the log4net project to the solution, I get the 
>> exception when creating an instance of the default LogRepository:
>>
>> rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); on 
>> line 412of DefaultRepositorySelector.cs
>>
>> this is my web.config:
>>
>> <?xml version="1.0"?>
>>
>> <configuration>
>>
>>   <configSections>
>>     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
>>   </configSections>
>>   <system.web>
>>     <compilation debug="true" targetFramework="4.0" />
>>     <trust level="High" />
>>   </system.web>
>>   <log4net debug="true">
>>     <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
>>       <file value="logfile.txt" />
>>       <appendToFile value="true" />
>>       <rollingStyle value="Date" />
>>       <datePattern value="yyyy-MM-dd" />
>>       <layout type="log4net.Layout.PatternLayout">
>>         <conversionPattern value="%date{dd-MM-yyyy HH:mm:ss,fff} [%-2p] - %C.%M - %m%n" />
>>       </layout>
>>
>>     </appender>
>>
>>     <root>
>>       <level value="ALL" />
>>       <appender-ref ref="RollingFileAppender" />
>>     </root>
>>   </log4net>
>>   <system.webServer>
>>      <modules runAllManagedModulesForAllRequests="true"/>
>>   </system.webServer>
>> </configuration>
>>
>> Other people suggest to add requirePermission=”false”to the section, 
>> but then the debugger won’t attach to the application pool.
>>
>> I hope someone can help me out of this problem.
>>
>> Regards,
>>
>> Dennis Minderhoud
>>

--

-- 
http://michelelepri.blogspot.com/

Stefan Bodewig | 15 May 06:05 2012
Picon

Re: [problem founded] Logger not working in an ASP.Net environment only works with full trust

On 2012-05-14, Michele Lepri wrote:

> Should I write in dev-list about it?

Yes, please do.  I'm not sure whether all people who'd be willing to
help are subscribed to this list.

Thanks

        Stefan


Gmane