Windows Service Logging - wix

I´ve a Windows Service and I want to log some information with NLog. My NLog file looks like:
<?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">
<time type="AccurateUtc" />
<targets>
<target name="debug-logfile" xsi:type="File" fileName="${specialfolder:folder=ApplicationData}/log/${date:format=yyyy-MM}.log" layout="${longdate} | ${level} | ${message}" />
<target name="trace-logfile" xsi:type="File" fileName="${specialfolder:folder=ApplicationData}/log/trace/${date:format=yyyy-MM-dd}.log" layout="${date:format=yyyy-MM-dd HH\:mm\:ss.fffffff} | ${level} | ${message}" />
<target name="errorfile" xsi:type="File" fileName="${specialfolder:folder=ApplicationData}/log/Error.log" layout="${longdate} | ${level} | ${message}" />
<target name="console" xsi:type="Console" layout="${longdate} | ${level} | ${callsite} | ${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="trace-logfile" />
<logger name="*" minlevel="Debug" writeTo="debug-logfile" />
<logger name="*" minlevel="Error" writeTo="errorfile" />
</rules>
</nlog>
Now the problem is, the %appdata% folder for my service is: C:\Windows\System32\config\systemprofile\AppData\Roaming and NLog can´t write into this folder. May someone tell me how to get access to this folder or change it to default ServiceProfile folder? (C:\Windows\ServiceProfiles\LocalService\AppData\Roaming\ATLED\log\trace)
I think it´s possible to change it when I give the service the local service user but it´s installed with WIX so may the problem be there. Here the WIX code sample:
<Component Id="CMP_Service" Feature="Core">
<File Source="$(var.Servie.TargetPath)" KeyPath="yes"/>
<ServiceInstall Id="ServiceInstallELS"
Name="Service"
Description="..."
Start="auto"
Account="[SERVICEACCOUNT]"
ErrorControl="normal"
Type="ownProcess"
Vital="no" />
<ServiceControl Id="ServiceControllELS"
Name="Service"
Start="install"
Stop="both"
Remove="uninstall"
Wait="no" />
</Component>
EDIT
With installutil.exe the service writes it´s logs into: C:\Windows\ServiceProfiles\LocalService\AppData\Roaming\ATLED\log\trace

I am new to NLog. But i faced similar issues when i used Log4Net with windows service . I was setting "appdata" path manually from the code. There must be a way in NLog also to set this path manually from code.
However when windows service runs as you mentioned it will take "appdata" path as the one you have mentioned.
To overcome this, i have used WMI windows API's. Please refer the below example.
Idea here is to get the UserName from WMI API's and construct the path manually .
private string GetWindowsUserAccountName()
{
string userName = string.Empty;
ManagementScope ms = new ManagementScope("\\\\.\\root\\cimv2");
ObjectQuery query = new ObjectQuery("select * from win32_computersystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query);
foreach (ManagementBaseObject mo in searcher?.Get())
{
userName = mo["username"]?.ToString();
}
userName = userName?.Substring(userName.IndexOf(#"\",StringComparison.InvariantCulture) + 1);
FCLogger.Logger.LogDebug("[ReturnWindowsUserAccountName]UserName Fetched:" + userName);
return userName;
}
You can construct path by your own , because only the UserName is unknown field here .
var userName = GetWindowsUserAccountName();
var appDataPath = Path.Combine(LoggerConstants.C, LoggerConstants.USERS, userName, LoggerConstants.APP_DATA, LoggerConstants.ROAMING);
//Ex: "C:\\Users\\" + userName from WMI +"\\AppData"+"\\Roaming" ;

Related

WiX installer: can we add a new element in web.config using a patch when it is set to NeverOverwrite=yes in its initial msi

I am working on a web application. the Web.config file is set to NeverOverwrite (=yes) in its initial installation. Now i need to add DBproviderfactories like below. Can i add this entire block using XmlFile in a patch.msp? I do not want to write a custom action. All I need is to add this block in the web.config. Any suggestion here is appreciated.
<system.data>
<DbProviderFactories>
<!-- Remove in case this is already defined in machine.config -->
<remove invariant="Oracle.ManagedDataAccess.Client" />
<add name="Oracle Data Provider for .NET" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.122.19.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
Sample: Maybe try this:
https://github.com/glytzhkof/WiXUpdateXmlFile
Below is the gist of it - please use the sample above for testing. The markup below is just for illustration.
Set the XML file both permanent and never overwrite.
See inline instructions in the sample above for testing.
Check what happens on uninstall - this markup will remove the entries it added.
<!-- Set app.config permanent and never overwrite to yes -->
<Component Feature="ProductFeature" NeverOverwrite="yes" Permanent="yes">
<File Source="app.config" />
</Component>
<!-- The XML update -->
<!-- Use a NEW GUID here, do not go live with this one -->
<Component Id="XmlFileUpdate" Guid="{00000000-0000-0000-0000-7405EED51B57}" Feature='ProductFeature'>
<!--Create New Element-->
<util:XmlFile Id='XmlSettings1' File='[INSTALLFOLDER]app.config' Action='createElement' Name='MyConfig' ElementPath='//configuration' Sequence='1' />
<!--Set New Value-->
<util:XmlFile Id='XmlSettings2' File='[INSTALLFOLDER]app.config' Action='setValue' Name='newVersion' Value='6.6.8' ElementPath='//configuration/MyConfig' Sequence='2' />
<!--Set New Value-->
<util:XmlFile Id='XmlSettings3' File='[INSTALLFOLDER]app.config' Action='setValue' Name='Server' Value='Pusevov' ElementPath='//configuration/MyConfig' Sequence='3' />
<!--Update Existing Value, Existing Element-->
<util:XmlFile Id='XmlSettings4' File='[INSTALLFOLDER]app.config'
Action='setValue' Name='newVersion' Value='7.7.7' ElementPath='//configuration/ExistingConfig/bindingRedirect' Sequence='4' />
<CreateFolder />
</Component>
</Directory>
</Directory>
Link:
Added new application setting to app.config but MSI won't install it (doesn't overwrite)

Parameters empty (or not supplied to CommandText) when using NLog with ASP.NET Core and SQLite

I've set up NLog in an ASP.NET Core MVC application using the examples in the documentation. Logging to a file (target=file) works without any problems.
However, logging to the Sqlite database results in an exception:
2018-10-30 20:04:41.4394 Error DatabaseTarget(Name=db): Error when
writing to database. Exception: System.InvalidOperationException: Must
add values for the following parameters: #MachineName, #Logged,
#Level, #Message, #Logger, #Callsite, #Exception at
Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior
behavior) at Microsoft.Data.Sqlite.SqliteCommand.ExecuteNonQuery()
at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo
logEvent) at NLog.Targets.DatabaseTarget.Write(LogEventInfo
logEvent)
Any ideas why the values of these parameters are empty? Or maybe the parameters are not passed at all?
NLog configuration 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">
<targets>
<target xsi:type="File" name="file" fileName="nlog-${shortdate}.log"
layout="${longdate}|${machinename}|${level:upperCase=true}|${logger}|${callsite}|${message} ${exception:tostring}" />
<target xsi:type="Database"
name="db"
dbProvider="Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite"
connectionString="Data Source=database.db;">
<commandText>
INSERT INTO Log (MachineName, Logged, Level, Message, Logger, CallSite, Exception)
VALUES (#MachineName, #Logged, #Level, #Message, #Logger, #Callsite, #Exception);
</commandText>
<parameter name="#MachineName" layout="${machinename}" />
<parameter name="#Logged" layout="${longdate}" />
<parameter name="#Level" layout="${level:upperCase=true}" />
<parameter name="#Message" layout="${message}" />
<parameter name="#Logger" layout="${logger}" />
<parameter name="#CallSite" layout="${callsite}" />
<parameter name="#Exception" layout="${exception:tostring}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file" />
<logger name="*" minlevel="Info" writeTo="db" />
</rules>
</nlog>
Unable to fix the issue using Microsoft.Data.Sqlite I switched to using System.Data.SQLite (NuGet) instead, which fixed the issue right away.
Remove the Microsoft.Data.Sqlite reference and add a reference System.Data.SQLite (1.0.109.2 at the time of writing) in your .csproj file. Update the dbProvider attribute value in nlog.config to System.Data.SQLite.SQLiteConnection, System.Data.SQLite and you're set.
nlog.config snippet:
<target xsi:type="Database"
name="db"
dbProvider="System.Data.SQLite.SQLiteConnection, System.Data.SQLite"
connectionString="Data Source=database.db;">
...
</target>

ArgumentOutOfRangeException during Build with Tools 12.0

We have an (old) build definition is using the UpgradeTemplate.xaml on TFS 2015 (and an underlying TFSBuild.proj which has a heap of custom actions). As such, the task of properly modernising the build is going to take time.
I'd like to hack the UpgradeTemplate to add in C#6/VB14 support without requiring a full re-write of the build definition, in order to keep the devs happy.
I attempted to edit the UpgradeTemplate.xaml to add a ToolPath property on the TfsBuild. However, now that I have done this, I get the following error on nearly all my projects:
ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length
On investigation, the lines of code in these projects all look like this:
<MSBuild.ExtensionPack.VisualStudio.TfsVersion TaskAction="GetVersion"
BuildName="$(BuildDefinition)" TfsBuildNumber="$(BuildNumber)"
VersionFormat="DateTime" DateFormat="MMdd" Major="$(MajorVersion)"
Minor="$(MinorVersion)">
The values of these variables as set printed out by Message tasks on the vbproj:
BuildDefinition: MyBuild-Testing
BuildNumber: 57902
MajorVersion: 43
MinorVersion: 2
The Build server has version 3.5.10 on the MSBuild ExtensionPack installed.
How do I resolve this issue? I'm testing this with a new build definition to allow devs to continue working while I get this set up, so I don't want to replace the ExtensionPack with the latest release (if possible) if it is likely to break the existing build.
Upgrade Template
<Activity mc:Ignorable="sad" x:Class="TfsBuild.Process" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mtbc="clr-namespace:Microsoft.TeamFoundation.Build.Client;assembly=Microsoft.TeamFoundation.Build.Client" xmlns:mtbw="clr-namespace:Microsoft.TeamFoundation.Build.Workflow;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbwa="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Activities;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbwt="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Tracking;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtvc="clr-namespace:Microsoft.TeamFoundation.VersionControl.Client;assembly=Microsoft.TeamFoundation.VersionControl.Client" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:sad="http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation" xmlns:sad1="clr-namespace:System.Activities.Debugger;assembly=System.Activities" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib" xmlns:this="clr-namespace:TfsBuild;" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<x:Members>
<x:Property Name="ConfigurationFolderPath" Type="InArgument(x:String)" />
<x:Property Name="AgentSettings" Type="InArgument(mtbwa:AgentSettings)" />
<x:Property Name="MSBuildArguments" Type="InArgument(x:String)" />
<x:Property Name="MSBuildPlatform" Type="InArgument(mtbwa:ToolPlatform)" />
<x:Property Name="DoNotDownloadBuildType" Type="InArgument(x:Boolean)" />
<x:Property Name="LogFilePerProject" Type="InArgument(x:Boolean)" />
<x:Property Name="SourcesSubdirectory" Type="InArgument(x:String)" />
<x:Property Name="BinariesSubdirectory" Type="InArgument(x:String)" />
<x:Property Name="TestResultsSubdirectory" Type="InArgument(x:String)" />
<x:Property Name="RecursionType" Type="InArgument(mtvc:RecursionType)" />
<x:Property Name="Verbosity" Type="InArgument(mtbw:BuildVerbosity)" />
<x:Property Name="Metadata" Type="mtbw:ProcessParameterMetadataCollection" />
<x:Property Name="SupportedReasons" Type="mtbc:BuildReason" />
</x:Members>
<this:Process.ConfigurationFolderPath>
<InArgument x:TypeArguments="x:String" />
</this:Process.ConfigurationFolderPath>
<this:Process.AgentSettings>[New Microsoft.TeamFoundation.Build.Workflow.Activities.AgentSettings() With {.MaxWaitTime = New System.TimeSpan(4, 0, 0), .MaxExecutionTime = New System.TimeSpan(0, 0, 0), .TagComparison = Microsoft.TeamFoundation.Build.Workflow.Activities.TagComparison.MatchExactly }]</this:Process.AgentSettings>
<this:Process.MSBuildArguments>
<InArgument x:TypeArguments="x:String" />
</this:Process.MSBuildArguments>
<this:Process.MSBuildPlatform>[Microsoft.TeamFoundation.Build.Workflow.Activities.ToolPlatform.Auto]</this:Process.MSBuildPlatform>
<this:Process.DoNotDownloadBuildType>[False]</this:Process.DoNotDownloadBuildType>
<this:Process.LogFilePerProject>[False]</this:Process.LogFilePerProject>
<this:Process.SourcesSubdirectory>
<InArgument x:TypeArguments="x:String" />
</this:Process.SourcesSubdirectory>
<this:Process.BinariesSubdirectory>
<InArgument x:TypeArguments="x:String" />
</this:Process.BinariesSubdirectory>
<this:Process.TestResultsSubdirectory>
<InArgument x:TypeArguments="x:String" />
</this:Process.TestResultsSubdirectory>
<this:Process.RecursionType>[Microsoft.TeamFoundation.VersionControl.Client.RecursionType.OneLevel]</this:Process.RecursionType>
<this:Process.Verbosity>[Microsoft.TeamFoundation.Build.Workflow.BuildVerbosity.Normal]</this:Process.Verbosity>
<this:Process.Metadata>
<mtbw:ProcessParameterMetadataCollection />
</this:Process.Metadata>
<this:Process.SupportedReasons>All</this:Process.SupportedReasons>
<mva:VisualBasic.Settings>Assembly references and imported namespaces serialized as XML namespaces</mva:VisualBasic.Settings>
<Sequence mtbwt:BuildTrackingParticipant.Importance="None">
<Sequence.Variables>
<Variable x:TypeArguments="mtbc:IBuildDetail" Name="BuildDetail" />
</Sequence.Variables>
<mtbwa:GetBuildDetail DisplayName="Get the Build" Result="[BuildDetail]" />
<mtbwa:InvokeForReason DisplayName="Update Build Number for Triggered Builds" Reason="Triggered">
<mtbwa:UpdateBuildNumber BuildNumberFormat="["$(BuildDefinitionName)_$(Date:yyyyMMdd)$(Rev:.r)"]" DisplayName="Update Build Number" />
</mtbwa:InvokeForReason>
<mtbwa:AgentScope DisplayName="Run On Agent" MaxExecutionTime="[AgentSettings.MaxExecutionTime]" MaxWaitTime="[AgentSettings.MaxWaitTime]" ReservationSpec="[AgentSettings.GetAgentReservationSpec()]">
<mtbwa:AgentScope.Variables>
<Variable x:TypeArguments="x:String" Name="buildDirectory" />
</mtbwa:AgentScope.Variables>
<mtbwa:GetBuildDirectory DisplayName="Get the Build Directory" Result="[buildDirectory]" />
<If Condition="[Not String.IsNullOrEmpty(ConfigurationFolderPath)]" DisplayName="If Not String.IsNullOrEmpty(ConfigurationFolderPath)">
<If.Then>
<mtbwa:TfsBuild BinariesSubdirectory="[BinariesSubdirectory]" BuildDirectory="[buildDirectory]" CommandLineArguments="[MSBuildArguments]" ConfigurationFolderPath="[ConfigurationFolderPath]" DisplayName="Run TfsBuild for Configuration Folder" DoNotDownloadBuildType="[DoNotDownloadBuildType]" LogFilePerProject="[LogFilePerProject]" RecursionType="[RecursionType]" SourcesSubdirectory="[SourcesSubdirectory]" TestResultsSubdirectory="[TestResultsSubdirectory]" ToolPath="C:\Program Files (x86)\MSBuild\12.0\Bin\" ToolPlatform="[MSBuildPlatform]" Verbosity="[Verbosity]" />
</If.Then>
</If>
<If Condition="[BuildDetail.CompilationStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Unknown]" DisplayName="If CompilationStatus = Unknown">
<If.Then>
<mtbwa:SetBuildProperties CompilationStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Succeeded]" DisplayName="Set CompilationStatus to Succeeded" PropertiesToSet="CompilationStatus" />
</If.Then>
</If>
<If Condition="[BuildDetail.TestStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Unknown]" DisplayName="If TestStatus = Unknown">
<If.Then>
<mtbwa:SetBuildProperties DisplayName="Set TestStatus to Succeeded" PropertiesToSet="TestStatus" TestStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Succeeded]" />
</If.Then>
</If>
</mtbwa:AgentScope>
<mtbwa:InvokeForReason Reason="CheckInShelveset">
<mtbwa:CheckInGatedChanges DisplayName="Check In Gated Changes" />
</mtbwa:InvokeForReason>
</Sequence>
</Activity>
In Particular, I added ToolPath="C:\Program Files (x86)\MSBuild\12.0\Bin\" to line 58.
TFSBuild.proj
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="DesktopBuild" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\SDC\Microsoft.Sdc.Common.tasks" />
<Import Project="$(MSBuildExtensionsPath)\ExtensionPack\MSBuild.ExtensionPack.tasks"/>
<ProjectExtensions>
<!-- Team Foundation Build Version - DO NOT CHANGE -->
<ProjectFileVersion>2</ProjectFileVersion>
</ProjectExtensions>
<PropertyGroup>
<RunCodeAnalysis>Never</RunCodeAnalysis>
<UpdateAssociatedWorkItems>false</UpdateAssociatedWorkItems>
<AdditionalVCOverrides></AdditionalVCOverrides>
<CustomPropertiesForClean></CustomPropertiesForClean>
<CustomPropertiesForBuild></CustomPropertiesForBuild>
<SkipGetChangesetsAndUpdateWorkItems>False</SkipGetChangesetsAndUpdateWorkItems>
<SkipWorkItemCreation>true</SkipWorkItemCreation>
<BuildConfigurationsInParallel>true</BuildConfigurationsInParallel>
<SkipDropBuild>false</SkipDropBuild>
</PropertyGroup>
<ItemGroup>
<SolutionToBuild Include="$(BuildProjectFolderPath)/SolutionsToBuild/Common.sln">
<Targets></Targets>
<Properties></Properties>
</SolutionToBuild>
</ItemGroup>
<ItemGroup>
<ConfigurationToBuild Include="Release|Any CPU">
<FlavorToBuild>Release</FlavorToBuild>
<PlatformToBuild>Any CPU</PlatformToBuild>
</ConfigurationToBuild>
</ItemGroup>
<PropertyGroup>
<SkipClean>false</SkipClean>
<SkipInitializeWorkspace>true</SkipInitializeWorkspace>
<ForceGet>true</ForceGet>
<IncrementalBuild>false</IncrementalBuild>
</PropertyGroup>
</Project>
Update
I think it might be something to do with running a private build (Latest + Shelveset). When I run a normal build, the BuildNumber variable is MyBuild-Testing_20170328.1. This appears to be working fine.
This issue is due to a difference between Private and Public builds. With Public Builds, the build is immediately numbered as BuildName_DateFormat.BuildNumber. Private builds however, are just numeric (e.g. 57902 above).
The Code in the extension does the following:
string buildstring = this.TfsBuildNumber.Replace(string.Concat(this.BuildName, "_"),
string.Empty);
char[] chrArray = new char[] { '.' };
string[] buildParts = buildstring.Split(chrArray, StringSplitOptions.RemoveEmptyEntries);
DateTime t = new DateTime(Convert.ToInt32(buildParts[0].Substring(0, 4),
CultureInfo.CurrentCulture),
Convert.ToInt32(buildParts[0].Substring(4, 2),
CultureInfo.CurrentCulture),
Convert.ToInt32(buildParts[0].Substring(6, 2),
CultureInfo.InvariantCulture));
Are you can see, its substringing on the build name, assuming it's been stripped down to the date component (20170328). Private builds aren't this long, and so fail.
This build works fine when running as a public build - basically it means that private builds on this definition are not available until an upgrade takes place.

NLog not logging (Windows Service)

I have a windows service that I am converting from my own logging to NLog. I have used NLog in a previous windows service application and felt that I knew what I was doing. But it isn't logging :(
I have the following NLog Configuration:
<?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="On" internalLogFile="c:\temp\nlog-internal.log" >
<variable name="DebugInfoLayout" value="[${date:format=MM/dd/yyyy h\:mm\:ss tt}] [${gdc:item=location}] | ${level} | ${message}" />
<variable name="InfoLayout" value="[${date:format=MM/dd/yyyy h\:mm\:ss tt}] ${gdc:item=SoftwareName} Version ${gdc:item=SoftwareVersion} - ${message}" />
<variable name="LogLayout" value="[${date:format=MM/dd/yyyy h\:mm\:ss tt}] ${message}" />
<variable name="logDir" value="${basedir}/LogFiles" />
<variable name="ArchiveDir" value="${basedir}/LogFiles/Archive" />
<targets async="true">
<target name="Errors" xsi:type="File" fileName="${logDir}/errors.log" layout="${LogLayout}" keepFileOpen="false" archiveFileName="${ArchiveDir}/errors_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30" archiveOldFileOnStartup="true" />
<target name="Info" xsi:type="File" fileName="${logDir}/info.log" layout="${InfoLayout}" keepFileOpen="false" archiveFileName="${ArchiveDir}/info_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30"/>
<target name="Debug" xsi:type="File" fileName="${logDir}/debug.log" layout="${DebugInfoLayout}" keepFileOpen="false" archiveFileName="${ArchiveDir}/debug_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30" />
</targets>
<rules>
<logger name="Errors" minlevel="Trace" maxlevel="Fatal" writeTo="Errors" />
<logger name="Info" minlevel="Trace" maxlevel="Warn" writeTo="Info" />
<logger name="Debug" minlevel="Trace" maxlevel="Fatal" writeTo="Debug" />
</rules>
</nlog>
To me, this looks correct. And it is the same as in my other application. From the code perspective, I have this in my service.vb file:
'NLog Instances
Dim errorLogger As NLog.Logger = NLog.LogManager.GetLogger("Errors")
Dim infoLogger As NLog.Logger = NLog.LogManager.GetLogger("Info")
Dim debugLogger As NLog.Logger = NLog.LogManager.GetLogger("Debug")
Then lower in the subroutines:
Try
Catch ex As Exception
WritetoNLog(errorlogger, NLog.LogLevel.Error, System.Reflection.MethodInfo.GetCurrentMethod.Name, ex.Message)
WritetoNLog(errorlogger, NLog.LogLevel.Error, System.Reflection.MethodInfo.GetCurrentMethod.Name, ex.InnerException.ToString)
End Try
And then for that simple routine:
Public Sub WritetoNLog(ByRef logger As NLog.Logger, ByVal nlogtype As NLog.LogLevel, ByVal location As String, message As String)
NLog.GlobalDiagnosticsContext.Set("location", String.Format("{0,-35}", location))
Select Case nlogtype
Case NLog.LogLevel.Trace
logger.Trace(message)
Case NLog.LogLevel.Fatal
logger.Fatal(message)
Case NLog.LogLevel.Info
logger.Info(message)
Case NLog.LogLevel.Debug
logger.Debug(message)
Case NLog.LogLevel.Error
logger.Error(message)
Case NLog.LogLevel.Warn
logger.Warn(message)
End Select
NLog.LogManager.Flush()
End Sub
This was a mistake internalLogLevel="On" should have been internalLogLevel="Trace" (or similar).

msbuild ITaskItem output

I'm trying to use MSBuild.ExtensionPack.Web.Iis7AppPool task with GetInfo task action.
This task's output parameter is SiteInfo property, which its type is ITaskItem. This is a propery, not a collection.
How can I access the SiteInfo metadata? I can access with $, but then all I can get is the web site name. I tried to use %(SiteInfo.) with no success.
If the output parameter is an ITaskItem and you want to access the metadata then you need to assign it to an ItemGroup instead of a Property.
<Target Name="Test">
<MSBuild.ExtensionPack.Web.Iis7AppPool
TaskAction="GetInfo"
Name="DefaultAppPool">
<Output TaskParameter="AppPoolInfo" ItemName="PoolInfo" />
</MSBuild.ExtensionPack.Web.Iis7AppPool>
<Message Text="AppPool info = [#(PoolInfo)]" />
<Message Text="AppPool MaxProcesses = [%(PoolInfo.MaxProcesses)]" />
<MSBuild.ExtensionPack.Web.Iis7WebSite
TaskAction="GetInfo"
Name="Default Web Site">
<Output TaskParameter="SiteId" PropertyName="WebId" />
<Output TaskParameter="SiteInfo" ItemName="WebInfo" />
</MSBuild.ExtensionPack.Web.Iis7WebSite>
<Message Text="WebSite id = [$(WebId)]" />
<Message Text="WebSite app pool = [%(WebInfo.ApplicationPoolName)]" />
</Target>