Skip to content

Instantly share code, notes, and snippets.

@j5alive
Last active June 7, 2017 08:54
Show Gist options
  • Save j5alive/03d16dc5c950a873b7073f77c2eb3b36 to your computer and use it in GitHub Desktop.
Save j5alive/03d16dc5c950a873b7073f77c2eb3b36 to your computer and use it in GitHub Desktop.
Raygun4Net automatic Breadcrumb logging with ASP.NET MVC
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using Mindscape.Raygun4Net;
using Mindscape.Raygun4Net.Breadcrumbs;
namespace Raygun.Examples
{
public class RaygunBreadcrumbAttribute : ActionFilterAttribute
{
public string CustomMessage { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var parameters = filterContext.ActionParameters;
var crumb = new RaygunBreadcrumb();
var controllerType = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType;
crumb.Message = CustomMessage ?? $"Executing {controllerType.Name}:{filterContext.ActionDescriptor.ActionName}";
crumb.Level = RaygunBreadcrumbLevel.Debug;
crumb.ClassName = controllerType.FullName;
crumb.MethodName = filterContext.ActionDescriptor.ActionName;
if (parameters != null)
{
foreach (var parameter in parameters)
{
crumb.CustomData.Add(parameter.Key, parameter.Value.ToDisplayString() ?? "NULL");
}
}
RaygunClient.RecordBreadcrumb(crumb);
base.OnActionExecuting(filterContext);
}
}
public static class Ext
{
public static string ToDisplayString<T>(this T instance) where T : class
{
if (instance == null)
return string.Empty;
Type instanceType = instance.GetType();
if (instanceType.IsPrimitive || instanceType == typeof (string))
{
return instance.ToString();
}
var strListType = typeof (List<string>);
var strArrType = typeof (string[]);
var arrayTypes = new[] {strListType, strArrType};
var handledTypes = new[] {typeof (int), typeof (long), typeof (string), typeof (bool), typeof (DateTime), typeof (double), typeof (decimal), strListType, strArrType};
var validProperties = instanceType
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(prop => handledTypes.Contains(prop.PropertyType))
.Where(prop => prop.GetValue(instance, null) != null)
.ToList();
return string.Format("{0}[{1}]", instanceType.Name,
string.Join(
", ",
validProperties.Select(prop => string.Format("{0}: {1}",
prop.Name,
(arrayTypes.Contains(prop.PropertyType) ? string.Join("|", (IEnumerable<string>) prop.GetValue(instance, null)) : prop.GetValue(instance, null))))
)
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment