This week .NET Framework 4.0 and Silverlight 4 have been released. I’ve updated NLog 2.0 to support them and published a new build – very experimental – on CodePlex. One of the biggest updates in Silverlight 4 is support for out-of-browser applications with elevated permissions,which means applications that can access the filesystem.
I’ve put together a Tiny sample that shows how to use NLog in Silverlight application. Basically since Silverlight does not have a concept of application configuration file you should configure Silverlight at application startup. In my case I’ve added this code in App.xaml.cs:
private void Application_Startup(object sender,StartupEventArgs E) { InitializeNLog(); this.RootVisual = new MainPage(); } private void InitializeNLog() { SimpleConfigurator.ConfigureForTargetLogging( new FileTarget() { Filename = @H_404_42@"${specialfolder:MyDocuments}/log.${shortdatE}.txt",Layout = new CsvLayout() { columns = { new Csvcolumn(@H_404_42@"Time",@H_404_42@"${longdatE}"),new Csvcolumn(@H_404_42@"Level",@H_404_42@"${level}"),new Csvcolumn(@H_404_42@"Lessage",@H_404_42@"${messagE}"),new Csvcolumn(@H_404_42@"Logger",@H_404_42@"${logger}"),},} },LogLevel.Debug); }
The application will produce CSV-formatted log file in Documents folder. The name of the file will be log.CURRENTDATE.txt.
Usage of NLog stays unchanged:
public partial class MainPage : UserControl { private static Logger logger = LogManager.GetCurrentClassLogger(); public MainPage() { InitializeComponent(); // log some events this.Loaded += (sender,E) => logger.Info(@H_404_42@"Page loaded"); this.Layoutupdated += (sender,E) => logger.Debug(@H_404_42@"Layout updated"); this.SizeChanged += (sender,E) => logger.Debug(@H_404_42@"Size changed to {0}x{1}",e.NewSize.Width,e.NewSize.Height); this.KeyDown += (sender,E) => logger.Debug(@H_404_42@"Key down '{0}'",e.Key); this.Unloaded += (sender,E) => logger.Info(@H_404_42@"Unloaded"); } private void button1_Click(object sender,RoutedEventArgs E) { logger.Info(@H_404_42@"Button clicked"); } }