.NET/C# Agent

Use the .NET Agent to post events to Loggr from a .NET desktop app or ASP.NET web app.

Before You Get Started
Installing From NuGet
Installing From Github
Tracking Users
Posting Events
Handling Exceptions
Extending The Agent
Other Configuration
Troubleshooting

Before You Get Started

Requirements

  • Microsoft .NET 2.0 Framework or greater is required.
  • Full version of the .Net Framework is required, client profiles will not work.

Other Notes

This agent support both asynchronous and synchronous posting of events to Loggr. We recommend posting asynchronously for better performance, but in some cases you may need to post synchronously. For example, if your posting from a console app the performs a short task, posts an event, then exits you will likely need to post synchronously because an async post will not complete before the app exits.

This agent also supports by VB.NET (and other .NET languages). We just use C# for the example code in this document.

top

Installing From NuGet

The preferred method of installation is using a NuGet package. If you don't use NuGet or you need to modify the source code of this agent, see Installing From Github.

Note

If you are new to NuGet or need to install it, see Installing Nuget from the Nuget.org website.


The first step is to install the package to your .NET app.

Visual Studio Package Manager
NuGet Package Manager If you use the Visual Studio Package Manager, as shown to the right, open the Package Manager by choosing Tools > Library Package Manager > Manage Nuget Packages...

From the left-hand accordian, choose Online > All.This will show you all packages available online. In the search box at the top-right, enter "loggr". You should see 2 packages. Select the package named loggr-dotnet and click the Install button. This will install the package for you.

Package Manager Console
If you install NuGet packages from the Package Manager Console, open the console and enter the following at the PM prompt.

PM> Install-Package loggr-dotnet

Edit web.config or app.config
To finish up you'll need to add your LOGKEY and APIKEY to your app's config file. NuGet will have added a couple lines to your config file, find the section in your config file that looks like:

  <loggr>
    <log>
      <!-- Get your logkey and apikey from your Loggr log settings-->
      <add key="logKey" value="__ADD_YOUR_LOGKEY_HERE__"/>
      <add key="apiKey" value="__ADD_YOUR_APIKEY_HERE__"/>
    </log>
  </loggr>

Replace the appropriately labeled values with your LOGKEY and APIKEY. Jump to Posting Events to continue.

top

Installing From Github

If you do not use NuGet or would like to tweak the agent for your own purposes, you can find pre-compiled binaries and source code on Loggr's Github page.

Add assembly to bin folder
Whether you grab the latest assembly from the bin folder on Github or you compile the source yourself, you'll need to copy the loggr-dotnet.dll assembly into your app's bin folder. After the file is copied, edit your app's config file.

Edit web.config or app.config
To finish up you'll need to add several lines to your app's config file. If you're building a web app, open web.config in a text editor. If you're building a desktop app, open app.config in a text editor (you may need to add this file if your project doesn't currently have one).

Add the following to the appropriate section of your config file:
<configuration>

  ...

  <configSections>
    <sectionGroup name="loggr">
      <section name="log" type="System.Configuration.NameValueSectionHandler"></section>
    </sectionGroup>
  </configSections>

  ...

  <loggr>
    <log>
      <add key="logKey" value="__ADD_YOUR_LOGKEY_HERE__"></add>
      <add key="apiKey" value="__ADD_YOUR_APIKEY_HERE__"></add>
    </log>
  </loggr>

  ...

</configuration>

Replace the appropriately labeled values with your LOGKEY and APIKEY. Jump to Posting Events to continue.

top

Tracking Users

It's really helpful to be able to see details and activity history for the users being assigned to an event. Use TrackUser(...) to register a user in your app. Once the user is registered, you'll be able to see their information when examinging an event on Loggr.

Note

We actually recommend putting a call like this on every web page in your website, within the JavaScript of your pages, but in some cases you'll want to do it on the server-side. If that's the case, use the following example. To see how to put in in your web pages, see our Javascript Agent



Each call to TrackUser(...) will register an action for a user.

using Loggr;

// the second and third arguments are optional
Loggr.Users.TrackUser(sUsername, sEmailAddress, "new account");

Once you make this call you should see, in realtime, the user under the Users tab in Loggr.

top

Posting Events

This agent uses a fluent-style interface for posting events to you Loggr log. Depending how you have your .NET project setup, you may need to tell your code to use the Loggr namespace like:

using Loggr;

The only value required for posting events is the Text property.

Loggr.Events.Create().Text("helloworld").Post();

Here's an example that shows how to post an event that utilizes all properties of an event. Keep in mind, you can use any combination that works for your app.

Loggr.Events.Create()
    .Text("More complex event: {0}", counter)
    .Link("http://loggr.net")
    .Tags("tag1 tag2")
    .Source(User.Identity.Name)
    .Value(35.50)
    .Data("<b>user-agent:</b> {0}<br/><b>on:</b> {1}", r.UA, DateTime.Now)
    .DataType(DataType.html)
    .Geo(40.1203, -76.2944)
    .Post();

Text Formatting
Notice in the previous post we pass an additional argument to the Text method. The Text, Link, Source, User and Data methods follow the .NET String.Format convention for formatting strings.

Loggr.Events.Create()
    .Text("Order for {0} '{1}' was placed", order.Quantity, order.Description)
    .Post();

These text methods also use another convention for formatting text. If you put a $$ within the string being passed to one of these methods, the agent will replace it with the previous value of the property, for example, the following will post "foo-bar".

Loggr.Events.Create()
    .Text("bar")
    .Text("foo-$$")
    .Post();

Appending Values
Certain methods also have a companion method for appending values. The Text, Tags and Data methods have AddText, AddTags and AddData. These methods also support the String.Format and $$ conventions.

Loggr.Events.Create()
    .Text("foo")
    .AddText("-bar")
    .Post();

Data Property
The Data property is just a string field, however you can specify a format for how the data should be handled. To specify the format, use the DataType property like:

Loggr.Events.Create()
    .Text("this event includes JSON data")
    .Data("{field1:true, field2:'hello'}")
    .DataType(DataType.json)
    .Post();

The DataType is prefixed to the actual data stored in your log. If you request the data for the previous event from our Web API you would get back:

@json
{field1:true, field2:'hello'}

Internally we parse out the DataType value when we display your event's data. We use it to show a formatted view of your data. The following table shows the currently recognized DataTypes (however, you can prefix your data with any DataType manually for your own purposes).

Value Description Prefix
DataType.plaintext Plain text data, no formatting (default)
DataType.html Text formatted as HTML @html
DataType.json Text formatted as JSON @json

Geo Property
The Geo property is used to geotag an event with location information, specifically latitude and longitude. The Geo method can be called two ways. The first way is to pass in actual latitude and longitude values.

Loggr.Events.Create()
    .Text("Picture was posted")
    .Geo(40.1203, -76.2944)
    .Post();

The other currently supported way is to pass an IP address and we'll try to figure out the latitude and longitude on the server.

Loggr.Events.Create()
    .Text("Picture was posted")
    .GeoIP("64.265.12.365")
    .Post();

Set LOGKEY and APIKEY programatically
By default, the agent will pull your LOGKEY and APIKEY from your config file. You may want to specify this in your code though.

Loggr.Events.Create()
    .Text("Picture was posted")
    .UseLog("LOGKEY", "APIKEY")
    .Post();

Manually Create and Post an Event
In some cases you may not want to use the fluent-style interface we provide. THe agent supports a standard interface for creating and posting events as well.

Event ev = new Event();
ev.Text = "this is an event";
ev.Value = 50;
ev.Tags.Add("tag1") 
ev.Geo = "40.1203,-76.2944"

LogClient cli = new LogClient("LOGKEY", "APIKEY");
cli.Post(ev);

top

Handling Exceptions

Using Loggr to track application exceptions is very helpful. It's even better when using the .NET agent because it automatically formats the exception event for you. All you have to do is trap an exception using a Try/Catch or within a global error handler and then post the exception to Loggr.

To post a .NET exception to Loggr use:

try 
{
    ## some code that generates an exception
} 
catch (Exception ex) 
{
    Loggr.Events.CreateFromException(ex).Post()
}

If you need to add any information to the event before posting, use the built-in methods:

Loggr.Events.CreateFromException(ex)
    .Text("This was an error: $$")
    .Source("myapp")
    .AddTags("critical")
    .Post()

You can easily log unhandled exceptions in an ASP.NET app. Edit the Global.asax.cs file. Add the following code to Application_Error event:

protected void Application_Error(object sender, EventArgs e)
{
    // get last exception
    Exception ExHttp = ((HttpApplication)sender).Server.GetLastError();

    // supress 404's
    if (ExHttp.GetType() == typeof(HttpException))
    {
        if (((HttpException)ExHttp).GetHttpCode() == 404)
            return;
    }

    // these are unhandled exceptions, so use the inner if available
    if (ExHttp.InnerException != null)
        ExHttp = ExHttp.InnerException;

    // post exception to Loggr
    Loggr.Events.CreateFromException(ExHttp).Post();
}

top

Extending The Agent

It's pretty common to want to override the Post() method of the fluent event to add things like default tags or other information. It's pretty easy to extend this agent to do just that.

The following code uses the name of the machine as the Source of every event posted.

class MyFluentEvent : FluentEventBase<MyFluentEvent>
{
    public override MyFluentEvent Post(bool Async)
    {
        // make sure we use our server name as the Source
        this.Source(System.Environment.MachineName);

        // now just post it
        return base.Post(Async);
    }
}

To use this new fluent event wrapper with the example above:

Loggr.Events.Create<MyFluentEvent>()
    .Text("This is a simple event")
    .Post()

top

Other Configuration

Besides the LOGKEY and APIKEY there are some other configuration options that can be added to your app.config or web.config.

Post over SSL
By default the agent will post your events to Loggr unencrypted. To have your events posted over SSL, set the secure setting to "true".

  <loggr>
    <log>
      ...
      <add key="secure" value="true"/>
      ...
    </log>
  </loggr>

Set defaults for event properties
In some cases you may want to provide default values for your event's properties. For example, some customers will use their server's name as Source property. You can set that up in code or you can set it in your config file.

If you set it in your config file it will only get used if the property is empty when posted. This allows you to override the behavior from code.

You can specify defaults for the Tags, Source and User properties.

  <loggr>
    <log>
      ...
      <add key="tags" value="tag1 tag2"/>
	  <add key="source" value="web1"/>
	  <add key="user" value="phil@here.com"/>
      ...
    </log>
  </loggr>

top

Troubleshooting

Using the .NET agent is pretty simple. Here are some things to help you figure out why it's not working.

You're not able to add the agent assembly as a reference to your app:
  • Make sure you're using at least version 2.0 of the .NET Framework.
  • Make sure you are not using the .NET Client Profile (use the full .NET Framework).
If you're posting events and they are not showing up in your event log, check the following:
  • Make sure your machine is connected to the internet.
  • Make sure the correct LOGKEY and APIKEY are configured in web.config (or app.config)?
  • Make sure you're looking at the correct day in the Loggr website.
  • Try posting synchronously, ex: .Post(false). See Before You Get Started.
  • Check your event log for any posting errors.

top