tags:

views:

49

answers:

4

I have a logging class that, well, logs things. I would like to add the ability to automatically have the current page be logged with the messages.

Is there a way to get the information I'm looking for?

Thanks,

+1  A: 

It's brittle and hard to test but you can use System.Web.HttpContext.Current which will give you a Request property which in turn has the RawUrl property.

blowdart
+1  A: 

From your class you can use the HttpContext.Current property (in System.Web.dll). From there, you can create a chain of properties:

The underlying object is a Page object, so if you cast it to that, then use any object you would normally use from within a Page object, such as the Request property.

rchern
There really is no need for a cast, HttpContext has a request property directly accessible.
blowdart
@blowdart, you're correct. I knew what I wanted to say, but it didn't come out right. I've edited - better?
rchern
Kind of - the underlying object may not be a page, custom handlers won't expose it as that, it depends on the mapping, so if the log is called from inside a handler that doesn't expose context as a page the cast would fail - hence it's better to avoid it in logging contexts, or at least wrap it in a check.
blowdart
A: 
public static class MyClass
{
    public static string GetURL()
    {
        HttpRequest request = HttpContext.Current.Request;
        string url = request.Url.ToString();
        return url;
    }
}

I tried to break it down a little :)

Robert
A: 

In the past I've also rolled my own logging classes and used Console.Writeln() but really there are a number of good logging options that already exist so why go there? I use NLog pretty much everywhere; it is extremely flexible with various log output destinations including console and file, lots of log format options, and is trivial to set up with versions targeting the various .net frameworks including compact. Running the installer will add NLog config file options to the Visual Studio Add New Item dialog. Using in your code is simple:

// declare in your class
private static Logger logger = LogManager.GetCurrentClassLogger();

...

// use in your code
logger.Debug(() => string.Format("Url: {0}", HttpContext.Current.Request.Url));
David Clarke