I would like to be able to write to a log the properties of various objects that I might pass to my LogEvent function. I have various objects defined, such as Town, Taxpayer, TaxedProperty, TaxAccount, etc. in my ASP.NET MVC application. I would like to write to some log passing in my object along with a bunch of other information.
I am writing this to a database table and I have a large text field in which I can insert a representation of the object that was being processed when a bad thing happened. Perhaps the user was trying to edit a taxpayer they did not have access to. So, I would write to the log that this user tried to access this taxpayer and I would do this:
kurantLogic.LogEvent(userName, null, null, Request.HttpMethod, "Taxpayers/Edit: Access denied because user does not have access to the taxpayer with ID=" + taxpayer.ID, false, taxpayer);
the last argument is the taxpayer object, but it could be some other object, such as a town. Here is another example:
kurantLogic.LogEvent(userName, null, null, Request.HttpMethod, "Towns/SetUpYourTown: Access denied because user does not have access to the town with ID=" + town.ID, false, town);
or here is an example of logging a good thing:
kurantLogic.LogEvent(userName, null, null, Request.HttpMethod, "Towns/SetUpYourTown: Success, Town edit saved = " + town.Name, false, town);
I would like to list out the fields in the town or taxpayer or whatever object is passed in without having to hard code all the properties of the thing I might pass in .
Here is my code that I started with:
public void LogEvent(string userName, int? userID, int? townID, string httpVerb, string description, bool isError, Object obj)
{
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MaxDepth = 1;
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
settings.NullValueHandling = NullValueHandling.Ignore;
string bigText = JsonConvert.SerializeObject(obj, settings);
LogEvent(userName, userID, townID, httpVerb, description, isError, bigText);
}
That kind of worked except that the JSON converter wrote out all the collections of things that the object contained, and I cannot find a way to suppress that. So, if there is a way to make JSON.SerializeObject include only the properties that are strings, ints, decimals, booleans, and not other objects, that would be a good solution. But I thought I could use Reflection to do it, but am having trouble with that.
My Taxpayer class has things like TaxedProperties that are associated with it, and I don't those logged. This is what I am getting now. At the end of this long JSON serialization you can see the simple properties listed.
Well, I could not post the JSON because StackOverflow thinks it looks like spam! I hope you can help.
I just want the "scalar" properties of the object logged without hard-coding. I would think that should be possible with either JSON or Reflection, but I am stumped.
Aucun commentaire:
Enregistrer un commentaire