mercredi 24 mars 2021

using(), access data from parent callee for logging purposes

I have a custom build log framework that logs to a database.

For example it can do

L.e("Error invalid password", userGuid);

This works fine for general use but the application is quite complex and there are a lot of different parts that are called from the main code. For example a login sequence could send an SMS for OTP which is handled by a completely other part of the system and it does not make sense to pass a lot of values thru just for logging purposes.

What I want to achieve is to tag the log with for example userGuid so that I can search for everything related to this specific user. I also want to tag any logging in the SMS module even though the SMS module does not know anything about the user concept.

So what I am thinking of is if it is possible to get the current threadid and store some things regarding the logging in a higher level. I wonder if this is at all possible.

Psuedo code:

void Login(UserName, Password) {
    User user = UserManager.GetUser(UserName)
    using(L.SetUser(user.ID)) {   //Here I want to use user.ID later in code that dont know the context
        SmsManager.SendOtp(user.Phonenumber)
    }
}

public class SmsManager {
    public static void SendOtp(string phonenumber) {
        if (phonenumber == "") {
            L.error("Phone number is empty");   //How can I use the value from L.SetUser above? Could I use a hash table of threadids in L or would that be a bad idea? 
        }
    }
}

Kind regards Jens

Aucun commentaire:

Enregistrer un commentaire