C
C#4mo ago
niels

Automate logging

In my ASP.NET application, I need to log that a certain action has taken place. Currently, I manually add a piece of code that does this. It takes information from the DbContext as well as the ServerCallContext. See the code snippet below, the relevant part is the adding of a row to the Auditlog. Is there a way to just automatically perform this action (e.g. by adding an attribute)? [Authorize(Policy = RightsConstants.TemplateControl)] public override Task<AddResponse> AddSmsTemplate(EyeClinicAdminShared.SmsTemplate request, ServerCallContext context) { var user = _dbContext.GetUser(); var clinic = _dbContext.GetClinic(); var template = _mapper.Map<Models.SmsTemplate>(request); template.Clinic = clinic; var entry = _dbContext.SmsTemplates.Add(template); _dbContext.AuditLogs.Add(new AuditLog { Action = "" + System.Reflection.MethodBase.GetCurrentMethod()?.Name, User = user, Clinic = clinic, IpAddress = context.Peer, RawData = request.ToString() }); _dbContext.SaveChanges(); return Task.FromResult(new AddResponse() {Id = entry.Entity.Id}); }
5 Replies
Pobiega
Pobiega4mo ago
no await :catsweat: and "doing this automatically"... well, there is something called interceptors in EF, but I'm not sure thats the best way here. We use an audit log at work too but its manual. the problem is how much info you need to create the audit info - you need multiple entries from the database itself, plus information about the specific request. I dont see you having access to this anywhere else but in the http pipeline. so that leaves you with either doing it manually, or doing it later in the http pipeline in your own middleware you could have that middleware check the actions attribute, and you'd pretty much get what you want
niels
niels4mo ago
Yeah thought something like that, thanks for the response Does that matter here?
Pobiega
Pobiega4mo ago
Absolutely. This code doesnt run async and you want your http endpoints to be fully async if possible so await any and all database operations, including SaveChangesAsync
niels
niels4mo ago
Ok thanks
Mayor McCheese
Mayor McCheese4mo ago
Most databases ( at some pricing tier ) support change data capture ( cdc ), audit is a bit of an overloaded concept, sometimes a code solution won't satisfy the requirements for auditing.