Where does log4net write log files when debugging a web application through Visual Studio? - visual-studio-2010

I'm trying to add log4net logging to a web application I'm writing. I've got this in a web service method:
log4net.Config.XmlConfigurator.Configure();
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Methods));
log.Info("Some information");
And this in the web.config file:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Windows" />
<identity impersonate="true"/>
</system.web>
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.RollFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.SimpleLayout" />
</appender>
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
I was expecting the log file to appear in the bin\ directory when I debug it through Visual Studio 2010, but nothing is written there. The method runs successfully without any exceptions, but I can't find the log file. Any ideas as to where it should appear?
Edit - Some extra info:
According to the notification area icon, the ASP.Net Development Server is running in:
C:\Users\jpope\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\
The permissions on this directory and the \bin\ sub-directory both give SYSTEM, me and Administrators full control, and no one else any access. The log file is not in the directory shown above or the \bin\ sub-directory.

If you're willing to wade into some low-level stuff, it might be interesting to see what Process Monitor thinks the web server process is trying to write to. At least it would be more fun than wading through the log4net documentation.

Maybe you should set the asp.net user has the write right for you web directory.

This turned out to be a configuration problem. Switching to a FileAppender instead of a RollFileAppender works fine. Now I need to find out what's wrong with the RollFileAppender configuration...
Edit: It's a RollingFileAppender, not a RollFileAppender.

Related

Disable DOTNET_STARTUP_HOOKS in ASP.NET Core 5 web app

When deploying my ASP.NET Core 5 app (which targets .NET 5) to an Azure App Service, it throws a 502 error with the following details logged:
<Event>
<System>
<Provider Name=".NET Runtime"/>
<EventID>1026</EventID>
<Level>1</Level>
<Task>0</Task>
<Keywords>Keywords</Keywords>
<TimeCreated SystemTime="2021-07-12T08:58:41Z"/>
<EventRecordID>-2033762671</EventRecordID>
<Channel>Application</Channel>
<Computer>RD0003FF7ABC48</Computer>
<Security/>
</System>
<EventData>
<Data>Application: dotnet.exe
CoreCLR Version: 5.0.721.25508
.NET Version: 5.0.7
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ArgumentException: Startup hook assembly 'C:\Program Files\dotnet\SDK\5.0.301\DotnetTools\dotnet-watch\5.0.301-servicing.21271.7\tools\net5.0\any\middleware\Microsoft.AspNetCore.Watch.BrowserRefresh.dll' failed to load. See inner exception for details.
---> System.IO.FileNotFoundException: Could not load file or assembly 'C:\Program Files\dotnet\SDK\5.0.301\DotnetTools\dotnet-watch\5.0.301-servicing.21271.7\tools\net5.0\any\middleware\Microsoft.AspNetCore.Watch.BrowserRefresh.dll'. The system cannot find the path specified.
File name: 'C:\Program Files\dotnet\SDK\5.0.301\DotnetTools\dotnet-watch\5.0.301-servicing.21271.7\tools\net5.0\any\middleware\Microsoft.AspNetCore.Watch.BrowserRefresh.dll'
at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly)
at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
at System.StartupHookProvider.CallStartupHook(StartupHookNameOrPath startupHook)
--- End of inner exception stack trace ---
at System.StartupHookProvider.CallStartupHook(StartupHookNameOrPath startupHook)
at System.StartupHookProvider.ProcessStartupHooks()
</Data>
</EventData>
</Event>
The path that is not found corresponds to the environment variable that is being set in the web.config, which is set automatically by VisualStudio when I build the app:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<!--App settings needed to the Cloud media service library-->
<system.web>
<customErrors mode="off" />
</system.web>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" startupTimeLimit="3600" requestTimeout="23:00:00">
<environmentVariables>
<environmentVariable name="COMPLUS_ForceENC" value="1" />
<environmentVariable name="ASPNETCORE_HTTPS_PORT" value="8088" />
<environmentVariable name="ASPNETCORE_AUTO_RELOAD_WS_ENDPOINT" value="ws://localhost:53593/MyWebApp/" />
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
<environmentVariable name="ASPNETCORE_HOSTINGSTARTUPASSEMBLIES" value="Microsoft.AspNetCore.Watch.BrowserRefresh" />
<environmentVariable name="DOTNET_STARTUP_HOOKS" value="**C:\Program Files\dotnet\SDK\5.0.301\DotnetTools\dotnet-watch\5.0.301-servicing.21271.7\tools\net5.0\any\middleware\Microsoft.AspNetCore.Watch.BrowserRefresh.dll**" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</configuration>
What is this environment variable used for? Can I disable its generation to allow the app run properly on the Azure App Service when deploying?
Thanks in advance.
Probably not the most fancy solution, but to manually delete the DLL referenced in the DOTNET_STARTUP_HOOKS environment variable in the web.config prevents VS to automatically set it over and over again.
Startup hooks are disabled by default on trimmed apps. Not sure if you're in the position to do app trimming, but if you could, that'd effectively disable startup hooks.
The main reason for this is explained here, and comes down to it being potentially dangerous to be run on trimmed apps.
Another, scarier way, would be to write yourself a global startup hook that disables local startup hooks to load. Of course, the simpler solution is to just make sure that that environment variable is not set in the first place.

Can't commit several files from Visual Studio project to subversion

Since a few weeks, I have some problems with Subversion. When I try to commit files from a Visual Studio 2017 project there are some files which I can't commit to my Visual SVN Server. To be precise all files in the project folder like *.cs, *.config, *.csproj, *.resx, ...
My setup:
Client: TortoiseSVN 1.9.7 on Windows10
Server: VisualSVN behind a IIS-ReverseProxy running on Windows Server 2012r2
The error I get when I try to commit for example a *.cs file:
Commit
D:\Test\branches\ScaraControl\ScaraControl\Form1.cs
D:\Test\branches\ScaraControl\ScaraControl\Form1.cs
Commit failed (details follow):
File 'D:\Test\branches\ScaraControl\ScaraControl\Form1.cs' is out of date
'/svn/Test/!svn/txr/5-9/branches/ScaraControl/ScaraControl/Form1.cs' path not found
You have to update your working copy first.
Updating the working copy is finishing successfully but doesn't fix the problem.
You can see my project in the picture below. For testing, I created a completely new and empty repository. As you can see the .vs, bin and obj folders are ignored with all the files inside of them, all other folders are committed to the server (without the files inside of them). In the second picture you can see that I can commit the *.sln file but no other file in the project folder.
For testing, I created an empty text file and renamed it to text.cs. Even this empty file cannot be committed to the Server with the same error message.
Due to the fact that this is happening to all Clients, it is more likely to be a problem on the Server side I guess but I have no idea what could cause this error. Unfortunately, the VisualSVN Server has no error logging or at least not the free version I'm using.
I would be very grateful for any tip I can get to solve this annoying problem.
Edit1: Problem is caused by the IIS Reverse-Proxy
After connecting via port 8443 directly to the VisualSVN server (bypassing the reverse proxy) everything is working again. So there must be a problem with the configuration of the URL Rewrite module. To be honest it took me quiet a long time to get it working somehow because my knowledge about all the settings is very limited.
This my Web.config with the settings for the URL Rewrite module. Maybe there is something not configured as it should be. If you need further information just ask.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<outboundRules>
<rule name="ReverseProxyOutboundRule1" preCondition="ResponseIsHtml1" enabled="true">
<match filterByTags="A, Form, Img" pattern="^http(s)?://svn.example.org:8443/(.*)" />
<action type="Rewrite" value="http{R:1}://svn.example.org/{R:2}" />
</rule>
<preConditions>
<preCondition name="ResponseIsHtml1">
<add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
</preCondition>
</preConditions>
</outboundRules>
<rules>
<rule name="ReverseProxyInboundRule1" enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{CACHE_URL}" pattern="^(https?)://" />
</conditions>
<action type="Rewrite" url="{C:1}://svn.example.org:8443/{R:1}" />
</rule>
</rules>
</rewrite>
<security>
<authorization>
<remove users="*" roles="" verbs="" />
<add accessType="Allow" users="" roles="Users" />
<add accessType="Allow" users="*" />
<add accessType="Allow" users="?" />
</authorization>
</security>
<urlCompression doStaticCompression="false" doDynamicCompression="false" />
<httpRedirect enabled="false" destination="https://svn.example.org" exactDestination="true" childOnly="true" />
<directoryBrowse enabled="false" />
</system.webServer>
</configuration>
I had the same issue.
The fails because IIS prohibits URL suffixes like .cs and .config
You can work around this by adding this to the web.config of the IIS proxy
<system.webServer>
<security>
<requestFiltering>
<fileExtensions allowUnlisted="true" applyToWebDAV="true">
<clear />
</fileExtensions>
<verbs allowUnlisted="true" applyToWebDAV="true" />
<hiddenSegments applyToWebDAV="true">
<clear />
</hiddenSegments>
</requestFiltering>
</security>
</system.webServer>
Credits to this post IIS7 and ARR as reverse proxy for Subversion
I came across the same problem and am running a reverse proxy through IIS, so believe that has something to do with it.
VisualSVN is served up locally on https://localhost:8443 and I was attempting to use the reverse proxy to route from https://svn.mysite.com. This appears to work fine. You can even checkout a fresh copy of the repo and all files are downloaded. It's when you try and commit that you have problems - as you've identified, certain files fail to be found on the repo.
The only work around I have found (thanks to your question narrowing down the likely causes) was to add the port to the URL: https://svn.mysite.com:8443. This shouldn't be necessary as the reverse proxy should handle, so I'm guessing it's an issue with VisualSVN which may be fixed in a future update.

Creating Environment-specific configuration files in VS-2010

I'm trying to create environment specific configurations in Visual Studio 2010 and can't get the transformations to occur for anything other then the App.config. Here is an example of my scenario:
Added a configuration file in my project (e.g. Configs\Log4Net.config). The file is set to "Content" and "Copy Always"
<log4net>
<root>
<appender-ref ref="EventLogAppender" />
<level value="DEBUG" />
</root>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
...
</appender>
</log4net>
Added a transformation configuration file (e.g. Configs\Log4Net.Release.config)
<log4net xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<root>
<level value="WARN" xdt:Transform="SetAttributes" xdt:Locator="XPath(log4net/root/level[#value!='WARN'])" />
</root>
</log4net>
Modified the VS Project file to include the following target
<UsingTask TaskName="TransformXml"
AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterPublish" Condition="exists('Configs\Log4Net.$(Configuration).config')">
<TransformXml Source="Configs\Log4Net.config"
Destination="$(OutputPath)\Configs\Log4Net.config"
Transform="Configs\Log4Net.$(Configuration).config" />
</Target>
I've followed a similar pattern for the App.config and that works fine, but this one does not appear to work. My expectation is that when I do a Release build, the log level should be set to WARN.
I'm using XmlPreprocess tool for config files manipulation. It is using one mapping file for multiple environments. You can edit mapping file by Excel. It is very easy to use.
Try to replace your TransformXml task with Exec task and call XmlPreprocess tool.

How to read sql generated by NHibernate in Visual Studio

According to what I know, there are 3 ways to read the sql script generated by NHibernate:
1. log4net
2. sql profiler
3. show_sql = true
Here I just want to talk about 3rd one for it's said that I can read the sql in the output window in Visual Studio. But whatever I do, I can see nothing?!
Becasue some guy said the "show_sql = true" just means "Console.WriteLine()", so I post a question here.
I have to say I don't get what I want, so here I summarize my questions:
in the output window in an web application:
Can the result of "Console.WriteLine()" be shown?
Can "show_sql=true" make the sql script be shown?
If yes, how?
I don't think Visual Studio will show console output for a class library or website project. What I do is configure log4net to write NHibernate's SQL to a text file, then open the file in Visual Studio. With the right configuration, VS will show updates to the file by clicking in the window.
In your Web.config (or app.config), define the log4net section, have NHibernate format the SQL nicely, create a text file appender, and direct NHibernate messages there:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="format_sql">true</property>
</session-factory>
</hibernate-configuration>
<log4net>
<appender name="NHibernateLogFile" type="log4net.Appender.FileAppender">
<file value="../Logs/NHibernate.log" />
<appendToFile value="false" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{HH:mm:ss.fff}%m%n==========%n" />
</layout>
</appender>
<logger name="NHibernate" additivity="false">
<level value="WARN" />
<appender-ref ref="NHibernateLogFile" />
</logger>
<logger name="NHibernate.SQL" additivity="false">
<level value="DEBUG" />
<appender-ref ref="NHibernateLogFile" />
</logger>
</log4net>
</configuration>
Then open up NHibernate.Log in Visual Studio. Because of the MinimalLock above, Visual Studio can read the file at the same time log4net is writing to it. When you click in the window, VS will reload the file. Just be sure to turn this off when you deploy the web site or application.

log4net only logs when running in the Visual Studio debugger

I'm running Visual Studio 2008 - and have a problem with log4net logging (v1.2.10).
I have a small console test program with a single log statement.
I have log4net configured for RollingLogFileAppender and ConsoleAppender.
When I run the compiled exe from the command line, I see the correct creation of the log file in my runtime directory. The log file is created (or appended to, when it exists), but the only output is the [Header] and [Footer] as configured. There is no output to console.
However, when I run under the debugger, the log message appears both in the log file and on the console. Following is my log4net configuration:
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="quicktest-log-" />
<appendToFile value="true" />
<immediateFlush value="true" />
<datepattern value="yyyy-MM-dd" />
<maxSizeRollBackups value="100" />
<maximumFileSize value="1048576" />
<rollingStyle value="Composite" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<header value="[Begin Quicktest program log]
" />
<footer value="[End Quicktest program log]
" />
<conversionPattern value="%date{HH:mm:ss} [%thread] %-5level %logger: %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
This theory could be a stretch, but have you ensured that the app.config has been copied to the folder where your executable is? App.config must be copied to where the output executable is, and you also must rename it to <executablename>.config, so if your executable is MyProgram.exe, config must be in MyProgram.exe.config.
It is working now, but the mystery remains. Apparently a bellyful of Chinese buffet is the only solution to a problem like this, for once I had one, the problem went away.
My test program was a single file with
class Test
{
static void Main (string[] args)
{
.
. // some logging attempted here.
.
}
}
When I had the problem originally, I was doing the logging within Main(). Afterwards, I created a method on the class Test, instantiated class Test in Main, and moved the logging to the method. This removed the problem:
class Test
{
static void Main (string[] args)
{
var p = new Test();
p.Go ();
}
public void Go ()
{
. // some logging here.
}
}
This is still inconclusive. I moved it back the way it was originally and it began working. So, I must conclude that the answer to this conundrum is: Do not attempt first-time log4net test programs without a bellyful of Chinese food.
I had the same issue, and I was doing clickonce deployment.
I found that i need to add log4net.xml in Project properties > Publish > ApplicationFiles and make this log4net.xml as datafile.

Resources