NLog File not Written while Debugging MVC3 Project - visual-studio-2010

NLog is not writing to the configured log file while debugging under VS 2010 SP1.
When I break at a line that should write to the log file:
logger.Error("My Log Message");
I can see all of the IsXyzEnabled (in particular IsErrorEnabled) are true, and logger.Factory.AllTargets[0].FileName is 'C:/MyValidPath/${shortdate}.log'.
The valid path is pre-created. I have not added any particular permissions to the path (I know that would be required under IIS... is it required under VS debugging and if so, which permissions?).
I have NLog configured (I think) to throw an Exception if anything goes wrong, and I do not receive an Exception after executing logger.Error().
NLog Config File:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<nlog throwExceptions="true" />
<targets>
<target xsi:type="File" name="f" fileName="C:/MyValidPath/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="f" />
</rules>
</nlog>

Related

How to allow write permission to AppPoolIdentity user in IIS 10

I have a website hosted on IIS 10. The website has a feature to write files in a folder. I have given write permission to IIS_IUSER, IUSER and USER groups on the wwwroot folder.However, I still see access denied exception.
One workaround I do is allowing write permission to AppPoolIdentity user (the user with name name as my application name) on the website folder. However, this permission gets removed each time I do a web deploy.
Is there something I am missing? I have windows server 2016.
If you use Web Deploy from Visual Studio, the publish will overwrite the ACLs on the server by clearing them to the inherited defaults of the parent.
To avoid update ACL each time when you publish your web application.
You could add below command in your PublishProfiles's pubxml.
<IncludeSetAclProviderOnDestination>False</IncludeSetAclProviderOnDestination>
Details publish profile as below:
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project. You can customize the behavior of this process
by editing this MSBuild file. In order to learn more about this please visit https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebPublishMethod>MSDeploy</WebPublishMethod>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
<ExcludeApp_Data>False</ExcludeApp_Data>
<MSDeployServiceURL>http://localhost:9825/</MSDeployServiceURL>
<DeployIisAppPath>WebFormApplication</DeployIisAppPath>
<RemoteSitePhysicalPath />
<SkipExtraFilesOnServer>True</SkipExtraFilesOnServer>
<MSDeployPublishMethod>InProc</MSDeployPublishMethod>
<EnableMSDeployBackup>False</EnableMSDeployBackup>
<UserName />
<_SavePWD>False</_SavePWD>
<IncludeSetAclProviderOnDestination>False</IncludeSetAclProviderOnDestination>
<PublishDatabaseSettings>
<Objects xmlns="">
<ObjectGroup Name="DefaultConnection" Order="1" Enabled="False">
<Destination Path="" />
<Object Type="DbCodeFirst">
<Source Path="DBContext" DbContext="WebFromIdentityTest.Models.ApplicationDbContext, WebFromIdentityTest" Origin="Configuration" />
</Object>
</ObjectGroup>
</Objects>
</PublishDatabaseSettings>
</PropertyGroup>
<ItemGroup>
<MSDeployParameterValue Include="$(DeployParameterPrefix)DefaultConnection-Web.config Connection String" />
</ItemGroup>
</Project>

NLog File is not creating After publishing the WEBAPI

I have Used NLog for logging and its working on local but when i published it then its not creating the log file while requesting the API. i have also set the
Copy to output directory = Copy always
Here is NLog.config File
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log" >
<!-- optional, add some variabeles
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->
<target xsi:type="File" name="DebugFile" fileName="${basedir}/logs/Debug_${shortdate}.log" layout="${longdate} ${threadid} ${uppercase:${level}} ${message}"/>
<target xsi:type="File" name="ErrorFile" fileName="${basedir}/logs/Error_${shortdate}.log" layout="${longdate} ${threadid} ${uppercase:${level}} ${message} ${newline} ${exception:format=tostring} ${newline}"/>
<!--
Writing events to the a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
</targets>
<rules>
<!-- add your logging rules here -->
<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
<logger name="*" levels="Debug,Info,Warn" writeTo="DebugFile" />
<logger name="*" level="Error" writeTo="ErrorFile" />
</rules>
</nlog>
Please tell me where i am doing wrong.

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.

Where does log4net write log files when debugging a web application through Visual Studio?

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.

log4net console app not logging on publish

I have a console app using log4net (via Castle Windsor). Everything logs fine to the console when I debug, but when I publish and run the app, nothing is logged.
I have my log4net configuration in a separate file (log4net.config).
I'm thinking it's not finding the config file, but that's just a guess.
I'm a web dev and haven't deployed many console apps. Am I missing something?
Do I need to manually copy the log4net.config file to the exe directory?
I'm on VS2010.
app.config:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false"/>
</configSections>
<appSettings>
...
<add key="log4net.Internal.Debug" value="false"/>
</appSettings>
<startup>
<supportedRuntime version="v2.0.50727"/></startup>
<castle>
<components>
...
</components>
<facilities>
<facility id="loggingfacility" configfile="log4net.config" loggingapi="log4net" type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging"/>
</facilities>
</castle>
</configuration>
log4net.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<root>
<!-- Value of priority may be ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF -->
<priority value="ALL" />
<appender-ref ref="ConsoleAppender" />
</root>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d: [%-5p] %m%n" />
</layout>
</appender>
<logger name="Castle">
<level value="INFO" />
</logger>
</log4net>
</configuration>
This is a wild guess, but have you marked "Build Action" of your log4net.config file as 'Content', and set it's property "Copy to Output directory" to "Copy always".
This way you don't have to copy file, and this file is considered as 'content' of the build output and will be included in your publish.

Resources