I have a WPF app that uses log4net. When I run it in Visual Studio, the log file is created in the Debug or Release folder as expected.
However, when I create an installer and run the installed app, the log file is not created. I added the following lines to the code...
string logFilePath = ((Hierarchy)LogManager.GetRepository())
.Root.Appenders.OfType<FileAppender>()
.FirstOrDefault()?.File;
using (StreamWriter sw = new StreamWriter(#"d:\log.log")) {
sw.WriteLine("Log file: " + logFilePath);
}
...to enable me to check that the log file was being written in the location I expected. It showed me that the log file was supposed to be written to C:\Program Files (x86)\Physio Diary\PhysioDiaryClient.log which is what I expected.
However, the file doesn't exist. Any idea why?
Here is the top of the App.config file...
<?xml version="1.0"
encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender"
type="log4net.Appender.RollingFileAppender">
<param name="File"
value="PhysioDiaryClient.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="2" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-7level %logger - %message%newline%exception" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
The bottom of the file looks like this...
<startup>
<supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
The bits in between are all to do with the WCF services that the app uses.
Anyone any ideas?
Edit: As a test, I tried hard-coding the log file path in App.config to my D: drive (so it's hard-coded, and no question of a permissions issue), but the file still wasn't created.
Thanks to #dymanoid for pointing me in the right direction. The log4net docs are a bit weak in this area, but I found this answer that pointed out that you can use normal environment variables in the config file.
With the aid of this list of environment variables, I ended up with the following...
<param name="File"
value="${LOCALAPPDATA}\Physio Diary\PhysioDiaryClient.log" />
This correctly write the file to C:\Users\MyUsername\AppData\Local\Physio Diary\PhysioDiaryClient.log
Hope this helps someone.
Related
I am using Specflow+ Runner for my automation testing using Selenium/Appium grid at the backend and want to test my scripts in parallel across multiple Browsers
I have referred to the examples from Specflow examples repository (https://github.com/SpecFlowOSS/SpecFlow.Plus.Examples/tree/master/SeleniumGridWebTest) and using the following Default.srprofile
<?xml version="1.0" encoding="utf-8"?>
<TestProfile xmlns="http://www.specflow.org/schemas/plus/TestProfile/1.5">
<Settings projectName="SpecflowTrial" />
<Execution stopAfterFailures="0" testThreadCount="5" testSchedulingMode="Sequential" retryCount="0" apartmentState="MTA" />
<Environment testThreadIsolation="Process" />
<TestAssemblyPaths>
<TestAssemblyPath>SpecflowTrial.dll</TestAssemblyPath>
</TestAssemblyPaths>
<Report>
<Template name="Report\ReportTemplate.cshtml" />
</Report>
<Targets>
<Target name="Browser_Safari">
<Filter>Browser_Safari</Filter>
<DeploymentTransformationSteps>
<EnvironmentVariable variable="Test_Browser" value="Safari" />
</DeploymentTransformationSteps>
<Environment testThreadIsolation="Process" />
</Target>
<Target name="Browser_Chrome">
<Filter>Browser_Chrome</Filter>
<DeploymentTransformationSteps>
<EnvironmentVariable variable="Test_Browser" value="Chrome" />
</DeploymentTransformationSteps>
<Environment testThreadIsolation="Process" />
</Target>
<Target name="Browser_Firefox">
<Filter>Browser_Firefox</Filter>
<DeploymentTransformationSteps>
<EnvironmentVariable variable="Test_Browser" value="Firefox" />
</DeploymentTransformationSteps>
<Environment testThreadIsolation="Process" />
</Target>
</Targets>
<TestThreads>
<TestThread id="0">
<TestAffinity>testpath:Target:Browser_Safari</TestAffinity>
</TestThread>
<TestThread id="1">
<TestAffinity>testpath:Target:Browser_Chrome</TestAffinity>
</TestThread>
<TestThread id="2">
<TestAffinity>testpath:Target:Browser_Firefox</TestAffinity>
</TestThread>
</TestThreads>
</TestProfile>
where the filters are applied to tags on the scenarios
My problem is that when running all tests in parallel, sometimes the tests are triggered across different browsers and sometimes it is triggered for the same Browsers, in this case, all run on either Chrome, Firefox or Safari.
What is the correct configuration that should be used to trigger tests in parallel across different browsers?
Update:
The above question was resolved bumping the SpecRun to version 3.6.2
I'm using a RollingFileAppender to log some info to a file with a conversionPattern (in the web.config) that looks like this for the header of each log section:
<conversionPattern value="%date - %property{userId} - %property{method}%newline--------------------------------%newline%message%newline%newline"/>
I'd like to log details under this header as bullet points. I'm currently trying to use another RollingFileAppender that logs to the same file with a simple conversionPattern of just a dash, like this:
<conversionPattern value="- %message%newline"/>
But these messages aren't making it into the log file. I'm using Log.Info() for the header and Log.Debug() for the bullet points and filtering each appender on their respective log levels. Is what I'm trying to do possible? Or is there a better way to get header and detail information into a log file from log4net?
Yes you can have two log4net appenders that append (write) to the same log file.
You need to place the following line in each of your Appenders:
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
This will make log4net use a minimal locking model that allows multiple processes to write to the same file.
Here's an example XML that uses two appenders writing to the same log file:
<log4net debug="false">
<appender name="RollingLogFileAppender1" type="log4net.Appender.RollingFileAppender">
<!-- this configures a log for the application messages -->
<file value="TestLog.log" />
<appendToFile value="true" />
<!-- next line uses a minimal locking model that allows multiple processes to write to the same file -->
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<!-- make the most recent log the highest numbered log -->
<countDirection value="1" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level %date{MM-dd-yyyy HH:mm:ss.ff} [%property{NDC}] %message%newline [Thread: %thread] %c{1} Method:%method(%file{1}, Line:%line) %newline" />
</layout>
<!-- The following two filters insure only log requests of
version '1' use this Appender -->
</appender>
<appender name="RollingLogFileAppender2" type="log4net.Appender.RollingFileAppender">
<file value="TestLog.log" />
<appendToFile value="true" />
<!-- next line uses a minimal locking model that allows multiple processes to write to the same file -->
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<!-- make the most recent log the highest numbered log -->
<countDirection value="1" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level %date{MM-dd-yyyy HH:mm:ss.ff} [%property{NDC}] [Thread: %thread] %c{1} Method:%method(%file{1}, Line:%line) %newline%message" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender1" />
<appender-ref ref="RollingLogFileAppender2" />
</root>
This can be found in the Apache documentation here:
Apache Log4Net Docs
Just search on this page for 'same file'.
Hope this helps.
You could realize if there is any problem with log4net checking the output window on visual studio. The library log errors there, very useful to detect configuration mistakes.
I followed youtube videos and articles on net and implemented this. But it never writes to my log file. Tried with all suggestions around many forums with no use.
not sure where I went wrong. I had this inside class library.
app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net><appender name="myLogAppender" type="log4net.Appender.RollingFileAppender" >
<file value="D:\\Log4NetLog.txt" /><layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level - %message%n" /></layout></appender>
<logger name="myLog"><level value="ALL"></level><appender-ref ="myLogAppender" />
</logger></log4net></configuration>
and in the Assembly.info.cs:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "app.config", Watch = true)]
and in the class file:
ILog mylog = LogManager.GetLogger("myLog");
string xx = "tokensalt";
mylog.Info(xx);
If you configuration is in you app.config, you do not need to specify the file in the Configurator:
[assembly: log4net.Config.XmlConfigurator()]
Also the watch is not very usefull, when you change the app.config file. The applpication will restart anyway and the file will be reloaded.
If that is not working, I would guess that the path you logging to is not accessible by the web user you are logging with.
->>> <file value="D:\\Log4NetLog.txt"
Make sure you choose a path where you have access.
Use the file appender and not the rolling appender, the rolling appender was made for backup purposes, for example if your file exceeds 10mb then it will write to your rolling appender and you can decide how many files of 10mb you write there, from the log4net site:
RollingFileAppender can roll log files based on size or date or both
depending on the setting of the RollingStyle property. When set to
Size the log file will be rolled once its size exceeds the
MaximumFileSize. When set to Date the log file will be rolled once the
date boundary specified in the DatePattern property is crossed. When
set to Composite the log file will be rolled once the date boundary
specified in the DatePattern property is crossed, but within a date
boundary the file will also be rolled once its size exceeds the
MaximumFileSize. When set to Once the log file will be rolled when the
appender is configured. This effectively means that the log file can
be rolled once per program execution.
Here is a working web.config example that should work for you:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.appender.FileAppender">
<file value="C:\MyLogs\MyLogFile.txt"/>
<appendToFile value="true"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{ABSOLUTE} [%logger] %level - %message%newline%exception"/>
</layout>
</appender>
<root>
<level value="DEBUG"></level>
<appender-ref ref="FileAppender"></appender-ref>
</root>
</log4net>
I am trying to understand how log4net works so I've added this to my app.config (I should add that Console Appender and FileAppender work perfectly, I only have trouble with the AdoNetAppender).
How can I debug this, to see if at least the connection to db succeeds?
The problem is the INSERT statement isn't executed.
I should add the
Data Source=MyWorkgroup\SQLEXPRESS;Initial Catalog=MyNewDatabase;User ID=juan;password=juan,
works perfectly when I try to connect to SQL Server manually, so not sure if that's the problem.
Also, the ConnectionType was taken from the official site:
https://logging.apache.org/log4net/log4net-1.2.11/release/sdk/log4net.Appender.AdoNetAppender.ConnectionType.html
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.log4netConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="AdoNetAppender"
type="log4net.Appender.AdoNetAppender">
<bufferSize value="10" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="Data Source=MyWorkgroup\SQLEXPRESS;Initial Catalog=MyNewDatabase;User ID=juan;Password=juan;Pooling=False" />
<commandText value="INSERT INTO Logs([logDate],[logThread],[logMessage]) VALUES(getdate(),'1','1')" />
<commandType value="Text" />
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="AdoNetAppender"/>
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Later edit (after using the debug method recommended by David):
haacked.com is indeed extremely interesting, great tip! However, it seems that it's describing what I'm instructing log4net to log, but not the result of those actions(?), if I'm reading this well (no failed/or succeeded?)
e.g.
log4net: Setting Property [ConnectionType] to String value
[System.Data.SqlClien t.SqlConnection, System.Data,
Version=1.0.3300.0, Culture=neutral, PublicKeyToke n=b77a5c561934e089]
log4net: Setting Property [ConnectionString] to String value [Data
Source=MyWorkgroup\SQLEXPRESS; Initial
Catalog=MyNewDatabase;
User ID=juan; Password=juan;
Pooling=False] log4net: Setting Property [CommandText] to String value [INSERT INTO Logs([logDate],[logThread],[logMessage]) VALUES(getdate(),'1','1')] log4net:
Setting Property [CommandType] to CommandType value [Text] log4net:
Created Appender [AdoNetAppender] log4net: Adding appender named
[AdoNetAppender] to logger [root]. log4net: Hierarchy Threshold []
Piece of code that helped me obtain this info (in case the site should become unavailable) is:
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\temp\log4netdiagn.txt" />
</listeners>
</trace>
</system.diagnostics>
I'm developing multiple Silverlight-Webparts in a single Solution in VisualStudio 2012 for SharePoint 2010.
Sometimes this error occurs in {Project1}:
Error occurred in deployment step 'Activate Features':
Failed to instantiate file "SiteAssets/{Project1Folder}/$SilverlightXapFile$"
from module "Designer": Source path "Features\{Project1Folder}\{otherProject}.xap" not found.
Elements.xml
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
<Module Name="{Module}" List="113" Url="_catalogs/wp">
<File Path="{Module}\{Webpart}.webpart" Url="{ProjectWebpart}.webpart" Type="GhostableInLibrary">
<Property Name="Group" Value="{Company}" />
</File>
</Module>
<Module Name="{Project}">
<File Path="{Project}\{Project1}.xap" Url="SiteAssets/{Project1Folder}/{Project1}.xap" />
<File Path="{Project}\{otherProject}.xap" Url="SiteAssets/{Project1Folder}/$SilverlightXapFile$" />
</Module>
</Elements>
Thanks to Subversion: I know Visual Studio added a line to Elements.xml of the {Project1} Webpart.
<File Path="{Project}\{otherProject}.xap" Url="SiteAssets/{Project1Folder}/$SilverlightXapFile$" />
When I delete this new line, it will work again.
My question:
How do I prevent VisualStudio from adding "wrong" references in Elements.xml to other Silverlight-Projects in the same solution?