Since I couldn’t find easily startup example for log4net written in VB.Net, I decided to write one for myself. In this example I’m using my favorite appender, the RollingFileAppender that has fixed file size and one automatic backup.
See also:- http://vpalmu.wordpress.com/2007/09/27/simplest-ever-example-for-log4net-and-vbnet/
- http://vpalmu.wordpress.com/2007/08/30/log4net-and-filename-com1txt/
Please download and install the last version of the log4net if you haven’t already done it. Create new windows application project.With VS2005 open, choose “File”, “New Project”. On New Project Window, choose “Windows application”,type “Log4NetApp” in the “Name” field, click ok. Open the Form1.vb, create five command buttons
- “Debug”
- “Info”
- “Warn”
- “Error”
- “Fatal”
Form1.vb should look something like this on design view:
Add reference to log4net.dll, can be found on \bin\net\2.0\release directory inside of the log4net installation directory.
Add followig code for Form1.vb:
Imports log4net
Public Class Form1
Dim log As log4net.ILog
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
log = log4net.LogManager.GetLogger("MyApp")
log4net.Config.XmlConfigurator.Configure()
End Sub
Private Sub cmdDebug_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDebug.Click
log.Debug("'Debug' level message")
End Sub
Private Sub cmdInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdInfo.Click
log.Info("'Info' level message")
End Sub
Private Sub cmdWarn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdWarn.Click
log.Warn("'Warning' level message")
End Sub
Private Sub cmdError_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdError.Click
log.Error("'Error' level message")
End Sub
Private Sub cmdFatal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdFatal.Click
log.Fatal("'Fatal' level message")
End Sub
End Class
Add application configuration file, right click Log4Net project on the Solution Explorer and choose “Add”, “New Item” and “Application Configuration File”. You can leave the default name app.config.
Open the App.config file, place under the configuration tag:
<configSections>
<section name=”log4net”
type=”log4net.Config.Log4NetConfigurationSectionHandler, log4net” />
</configSections>
Create new tag <log4net></log4net> under the </configSections> Open the tag, and place following inside of it:
<appender name=”RollingFileAppender” type=”log4net.Appender.RollingFileAppender”>
<file value=”c:\\log.txt” />
<appendToFile value=”true” />
<rollingStyle value=”Size” />
<maxSizeRollBackups value=”3″ />
<maximumFileSize value=”100KB” />
<staticLogFileName value=”true” />
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%date [%thread] %-5level %logger [%property{NDC}] – %message%newline” />
</layout>
</appender>
This defines the log appender that is going be used for your log (see doubles slashes for file value).
And finally, still inside the <log4net> tab, the logger tab ties the .config file with your app, make sure that de logger name defined here is the same that you used for GetLogger method earlier.
<logger name=”MyApp”>
<level value=”DEBUG” />
<appender-ref ref=”RollingFileAppender” />
</logger>
Close the log4net tag with </log4net>. Save everything and start your app with full compilation. When window show up click on the debug button and you should see your message on “c:\log.txt” file.
Change the level value on the logger tag in the app.confifg file from “DEBUG” to “ERROR”. After this all ”DEBUG”, “INFO” and “WARN” level messsages should have been filtered out.











September 27, 2007 at 1:02 am
Can you help me ? Please
How to apply the log4net with Infopath Solution (using VS 2005 Tool for Application and Office – VSTA, VSTO)?
Thanks
September 27, 2007 at 12:00 pm
Amie,
Unfortunatelly I don’t know much about programming with VSTO, so I can’t help you on that. But I just wrote another post about log4net that may provide some help for you. If you try the example on my post with your VSTO app , and it works, it might mean that you have some problems with configuration files and log4net initialization..I have struggled a lot with those
Here’s the post:
http://vpalmu.wordpress.com/2007/09/27/simplest-ever-example-for-log4net-and-vbnet/
July 23, 2008 at 10:04 pm
Hi,
Thanks for this post. I am trying to use the logging feature for a webservice that I developed in VB.NET but it does not work.
Could you please post sample code for web service developed in VB.NET?
Here are some notable differences:
I added the following in the Global.asax
=============================
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
‘ Code that runs on application startup
log4net.Config.XmlConfigurator.Configure()
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
‘ Code that runs on application shutdown
log4net.LogManager.Shutdown()
End Sub
In the service.asmx file
================
Public Class Service
Inherits System.Web.Services.WebService
Private Shared log As ILog = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
I stored the log4net configuration information in the Web.Config.
Thanks for your help in advance.
Jawahar
October 29, 2008 at 6:29 am
A very useful example – thank you! Log4net is baffling anyway to the newbie.
December 5, 2008 at 8:59 am
Hi, I get an error on my vb app at the line log4net.Config.XmlConfigurator.Configure(). It is log4net:ERROR XmlConfigurator: Failed to find configuration section ‘log4net’ in the application’s .config file. Check your .config file for the and elements. The configuration section should look like: .
Can you please,help me? Thank you.
February 13, 2009 at 6:35 pm
Hi Franco,
Please post your config file here if you still have this problem..
April 27, 2009 at 5:54 am
[...] VPalmu: Simple Log4Net example with VB.Net [...]
May 10, 2011 at 6:28 pm
Nice post.
Congrats
June 6, 2011 at 6:28 pm
================ERROR===============
STACK
log4net:ERROR DefaultRepositorySelector: Exception while reading ConfigurationSettings. Check your .
config file is well formed XML.
System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize —> Sy
stem.Configuration.ConfigurationErrorsException: Only one element allowed per confi
g file and if present must be the first child of the root element. (C:\Users\ABS-Dav
o\Documents\Visual Studio 2008\Projects\EjemploMultiEscritura\EjemploMultiEscritura\bin\Debug\Ejempl
oMultiEscritura.exe.Config line 25)
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
— End of inner exception stack trace —
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
at System.Diagnostics.DiagnosticsConfiguration.Initialize()
at System.Diagnostics.DiagnosticsConfiguration.get_IndentSize()
at System.Diagnostics.TraceInternal.InitializeSettings()
at System.Diagnostics.TraceInternal.WriteLine(String message)
at log4net.Util.LogLog.EmitErrorLine(String message)
log4net:ERROR DefaultRepositorySelector: Exception while reading ConfigurationSettings. Check your .
config file is well formed XML.
=============== app.confo ==============
<!—->
<!– –>
June 6, 2011 at 6:29 pm
<!—->
<!– –>
October 28, 2011 at 5:53 am
What a really great blog post.