Send mail to the author(s) E-mail

# Wednesday, 07 August 2013
( NLog | this.Log )

Log to the output window in VS

<!--<target name="debugger" xsi:type="Debugger" layout="${logger}::${message}"/>—>

<!-- See output window in VS-->
<!--<logger name="*" minlevel="Debug" maxlevel="Warn" writeTo="debugger" />—>


<target type="Database" name="database" connectionStringName="DBConnect">
    insert into Log ([CreateDate], [Origin], [LogLevel], [Message], [Exception], [StackTrace]) values (@createDate, @origin, @logLevel, @message, @exception, @stackTrace);
  <parameter name="@createDate" layout="${date}"/>
  <parameter name="@origin" layout="${logger}"/>
  <parameter name="@logLevel" layout="${level}"/>
  <parameter name="@message" layout="${message}"/>
  <parameter name="@exception" layout="${exception:format=Message,StackTrace}"/>
  <parameter name="@stackTrace" layout="${stacktrace}"/>
  <parameter name="@stackTrace" layout=""/>


<logger name="*" appendTo="database"/>

NLog Errors

Very useful for debugging why something is not logging.

<nlog xmlns="" xmlns:xsi="" throwExceptions="true" internalLogFile="c:\temp\nlog.txt" internalLogLevel="Debug">

| | # 
# Wednesday, 10 July 2013
( NLog | this.Log )

  • It does no logging if you don’t have a logging engine set up.
  • It works everywhere in your code base (where you can write C#). This means in your razor views as well!
  • It uses deferred execution, which means you don’t have to mock it to use it with testing (your tests won’t fail on logging lines).
  • You can mock it easily and use that as a means of testing.
  • You have no references to your actual logging engine anywhere in your codebase, so swapping it out (or upgrading) becomes a localized event to one class where you provide the adapter.

I’ve been using NLog as the engine.


Use NuGet to pull down this.log and NLog

public class SomeClass { 
  public void SomeMethod() { 
    this.Log().Info(() => "Here is a log message with params which can be in Razor Views as well: '{0}'".FormatWith(typeof(SomeClass).Name)); 
    this.Log().Debug("I don't have to be delayed execution or have parameters either"); 
  public static void StaticMethod() { 
    "SomeClass".Log().Error("This is crazy, right?!"); 

and to setup:


and in App.Config

<nlog xmlns="" xmlns:xsi="">
      <target name="file" type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
        <!--<target type="File" fileName="${basedir}/logs/UER.Web.log" layout="${longdate} | ${pad:padding=-4:inner=${threadid}}| ${pad:padding=-10:inner=[${level:uppercase=true}]}| ${pad:padding=-50:inner=${logger}}| ${message}" archiveFileName="${basedir}/logs/UER.Web-archive-{#}.log" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="14" concurrentWrites="true" keepFileOpen="false" encoding="iso-8859-2" />-->
        <target type="File" fileName="e:/temp/UER.Web.log" layout="${longdate} | ${pad:padding=-4:inner=${threadid}}| ${pad:padding=-10:inner=[${level:uppercase=true}]}| ${pad:padding=-50:inner=${logger}}| ${message}" archiveFileName="${basedir}/logs/UER.Web-archive-{#}.log" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="14" concurrentWrites="true" keepFileOpen="false" encoding="iso-8859-2" />
      <target name="file-exceptions" type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
        <target type="File" fileName="${basedir}/logs/UER.Web-exceptions.log" layout="${longdate} | ${machinename} | ${processinfo:property=ProcessName} | ${threadid}|[${level:uppercase=true}] | (${logger})${newline}[START]${newline}${message}${newline}[END]" archiveFileName="${basedir}/logs/UER.Web-exceptions-archive-{#}.log" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="14" concurrentWrites="true" keepFileOpen="false" encoding="iso-8859-2" />

      <!--<target name="console" type="ColoredConsole" layout="${longdate} [${level:uppercase=true}] ${message}">
        <highlight-row backgroundColor="NoChange" condition="level = LogLevel.Error" foregroundColor="Red" />
        <highlight-row backgroundColor="NoChange" condition="level = LogLevel.Warn" foregroundColor="Yellow" />
      <!--<target name="errorSmtp" type="Mail" layout="${longdate} ${threadid} [${level:uppercase=true}] ${logger} - ${message}" subject="this.Log Sample Console Errors - LOCAL DEBUG" to="" from="" smtpServer="localhost" />-->
      <logger name="*" minlevel="Debug" maxlevel="Warn" writeTo="file" />
      <!--<logger name="*" minlevel="Debug" maxlevel="Warn" writeTo="console" />-->
      <logger name="*" minlevel="Error" maxlevel="Fatal" writeTo="file-exceptions" />
      <!--<logger name="*" minlevel="Error" writeTo="errorSmtp" />-->

When using Resharper’s test runner, I used e:/temp to dump log files to, with permissions set to everyone writeable.

| | # 
# Wednesday, 13 March 2013
# Tuesday, 20 September 2011
( Git | Glimpse | MVC | Ninject | NLog | VidPub )

Notes from TekPub ASP.NET MVC3 series of tutorials.

  • Startup – big idea.. charge people money for
  • Good idea, well executed
  • Get site out there and pay the bills!

Why MVC3 in this Fast Paced Startup?

  • Good stable version of MVC
  • I know C#

What are we doing (Elevator pitch) and when are we going to do it?

1 sentence!

Platform and Tools


Unfuddle for project mgt


or agilezen (kanban)

Source is on

Setup a new MVC3 solution called VidPub.Web


Lib is for external dlls.  Docs are for docs.  Everything is under git

git init in \dev\VidPub

git add .

git commit –am “Initial load”


mkdir e:\dropbox\repositories\vpub


in e:\dropbox\repositories\vpub

git init –bare

from \dev folder  git push origin master


So other people can then pull from that repository… it is the whole repo up there, not just source.

Test Project

Have just created a container.


Don’t want concurrent authentcation.. ie users sharing accounts.  Could use token based.

Now, 1 Year, 3 Years

ASP.NET Membership – complicated..

Consistency of FileNames



no more content directory

Model\AccountModels.cs to AccountModel

change CSS path in _Layout.cshtml



make faster for user as they may have this cached in their browser.  Also save us a bit of bandwidth.  Cache up to a year.

If using Azure to host MSDN have got some benefits.


NLog using NuGet

Code Snippet
<nlog xmlns="" xmlns:xsi="" >

    <!--Useful for debugging-->
    <target name="console" xsi:type="ColoredConsole"
     layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />

    <target name="file" xsi:type="File" fileName="${basedir}/App_Data//logs/site.log"
     layout="${date}: ${message}" />

    <target name="eventlog" xsi:type="EventLog" source="My App" log="Application"
    layout="${date}: ${message} ${stacktrace}" />



    <logger name="*" minlevel="Info" writeTo="file" />
    <logger name="*" minlevel="Fatal" writeTo="eventlog" />



in dev we’re going to log everything to a file in App_Data/logs

In \Infrastructure we’ve got some code to help us log with an interface extracted.

Code Snippet
public class NLogger : VidPub.Web.Infrastructure.Logging.ILogger {
        Logger _logger;
        public NLogger() {
            _logger = LogManager.GetCurrentClassLogger();
        public void LogInfo(string message) {

        public void LogWarning(string message) {

        public void LogDebug(string message) {

        public void LogError(string message) {
        public void LogError(Exception x) {
        public void LogFatal(string message) {
        public void LogFatal(Exception x) {
        string BuildExceptionMessage(Exception x) {

            Exception logException = x;
            if (x.InnerException != null)
                logException = x.InnerException;

            string strErrorMsg = Environment.NewLine + "Error in Path :" + System.Web.HttpContext.Current.Request.Path;

            // Get the QueryString along with the Virtual Path
            strErrorMsg += Environment.NewLine + "Raw Url :" + System.Web.HttpContext.Current.Request.RawUrl;

            // Get the error message
            strErrorMsg += Environment.NewLine + "Message :" + logException.Message;

            // Source of the message
            strErrorMsg += Environment.NewLine + "Source :" + logException.Source;

            // Stack Trace of the error

            strErrorMsg += Environment.NewLine + "Stack Trace :" + logException.StackTrace;

            // Method where the error occurred
            strErrorMsg += Environment.NewLine + "TargetSite :" + logException.TargetSite;
            return strErrorMsg;


So we don’t have anything coupled tightly right from the start (eg logging which we’re doing next).. lets use IoC


Wire up in global.asax

 public class MvcApplication : NinjectHttpApplication  {

**NO this is not correct as in MVC3 it is bootstrapped, so just leave as:

public class MvcApplication : System.Web.HttpApplication {

Setting up logging in App_Start bootstrapper file.

“Every time you see a request for ILogger interface in a controller, return a new NLogger class”



added in Logs/Site.log into our project.


Added in bookmarks into bar to turn on and off.


git add .

git commit –am “Added logging, IoC and rearranged stuff”

git push origin master (to save to dropbox)


current state of play of our filesystem.


| | #