3

I am using Log4net (v2.0.50727) within a C# webservice I have written. Its configured to create 2 appenders. The first is a general debug file that I monitor to ensure the service is running correctly, the second is a report that I forward onto a customer at various intervals (manually now, but may get automated).

<log4net>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="..\logs\Service.log.xml"/>
    <appendToFile value="true"/>
    <rollingStyle value="Size"/>
    <maxSizeRollBackups value="20"/>
    <maximumFileSize value="10000KB"/>
    <staticLogFileName value="true"/>
    <preserveLogFileNameExtension value="true" />
    <layout type="log4net.Layout.XmlLayoutSchemaLog4j">
      <conversionPattern value="%utcdate [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
    </layout>
  </appender>
  <appender name="CustomerReportAppender" type="log4net.Appender.RollingFileAppender">
      <file value="..\logs\Customer.Report.xml"/>
      <appendToFile value="true"/>
      <rollingStyle value="Size"/>
      <maxSizeRollBackups value="20"/>
      <maximumFileSize value="10000KB"/>
      <staticLogFileName value="true"/>
      <preserveLogFileNameExtension value="true" />
      <layout type="log4net.Layout.XmlLayoutSchemaLog4j">
        <conversionPattern value="%utcdate [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
      </layout>
  </appender>
  <root>
    <level value="DEBUG"/>
    <appender-ref ref="RollingFileAppender"/>
  </root>
  <logger name="CustomerReport">
    <level value="ALL" />
    <appender-ref ref="CustomerReportAppender" />
  </logger>
</log4net>

The logging to both files works OK. The problem is that if I send the Customer.Report.xml file to my customer, it wont open in Excel as its not valid XML. The file consists of multiple lines of event elements -

<event logger="CustomerReport" timestamp="1453717399436" level="INFO" thread="8">
<message>Customer Info</message>
<properties>
<data name="UserName" value="IIS APPPOOL\Customer Service" />
<data name="log4jmachinename" value="MyServer" />
<data name="log4japp" value="/LM/W3SVC/3/ROOT-2-130981905203581113" />
<data name="HostName" value="MyServer" />
</properties>
</event>

I assume Excel is complaining as it doesnt have 1 root element. If I wrap the whole file in -

<Report>
....
</Report>

then Excel loads it OK. Is it possible to get Log4net to generate this for me ? Or can Excel be made to handle it ? Thank you.

2
  • You could add header and footer elements to the layout (note that your conversion pattern is ignored as XmlLayoutSchemaLog4j has no such property) - or you have various options to take more control over the process, eg a custom appender or custom Layout,
    – stuartd
    Jan 26, 2016 at 16:11
  • Log4net can't handle this by itself because the RollingFileAppender has no determined end. It can't possibly know when to close the root xml tag. You could handle this from Excel by using VBA if that's acceptable for your users (you do get these virus warnings), or you would have to intervene with some custom code. Jul 31, 2016 at 7:47

1 Answer 1

1

PowerShell is a great tool to quickly solve this sort of thing.

Not sure if this is the type of answer you're looking for but it would solve your problem in an intermediate way. You've mentioned that you're doing this manually right now, but might automate it in the future - PowerShell would also be a great way to do that.

So the script below will ask you to select the file and then automatically places its XML content inside of a root element that you specify:

[CmdletBinding()]
Param(
    [Parameter(ValueFromPipeline=$true)]
    [ValidateScript({Test-Path $_ -PathType Container})]
    [string]
    $InitialDirectory,

    [ValidateNotNullOrEmpty()]
    [string]
    $RootElementName = 'Report'
)

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.Filter = "XML (*.xml)| *.xml"
$OpenFileDialog.ShowDialog() | Out-Null

$FileName = $OpenFileDialog.FileName
$FileContent = Get-Content $FileName

$FileContentXml = [Xml]$FileContent

[XML.XMLDocument]$XMLDocument = New-Object System.XML.XMLDocument
[XML.XMLElement]$XMLRoot = $XMLDocument.CreateElement($RootElementName)
$XMLRoot.InnerXml = $FileContentXml.OuterXml
$XMLDocument.AppendChild($XMLRoot)

$XMLDocument.Save($FileName)

You would use it by saving this script in a new file, e.g. D:\Add-RootXmlElement.ps1, and then you could run it from a cmd prompt like so:

@powershell D:\Add-RootXmlElement.ps1 -InitialDirectory "D:\Logs" -RootElementName "Report"

Adjust the default values in the Param block as appropriate in order to save yourself some typing in the future.

Does this solve your problem?

EDIT:

Of course, if you want to automate this and you know the file name at the time you're calling the script, just omit the entire $InitialDirectory and $OpenFileDialog parts, and simply set the $FileName directory to the path of the log file you want to add a root element to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.