Log & gestion des erreurs
Journalisation
Casbin uses the built-in log
to print logs to the console by default, like:
2017/07/15 19:43:56 [Demande: alice, data1, read ---> true]
Logging is not enabled by default. Vous pouvez le basculer via Enforcer.EnableLog()
ou le dernier paramètre de NewEnforcer()
.
We already support logging the model, enforce request, role, and policy in Golang. Vous pouvez définir votre propre journal de connexion Casbin. Si vous utilisez Python, pycasbin utilise le mécanisme de journalisation par défaut de Python. The pycasbin package makes a call to logging.getLogger()
to set the logger. Aucune configuration spéciale de journalisation n'est nécessaire autre que l'initialisation du logger dans l'application parente. If no logging is initialized within the parent application, you will not see any log messages from pycasbin. At the same time, when you enable log in pycasbin, it will use the default log configuration. For other pycasbin extensions, you can refer to the Django logging docs if you are a Django user. For other Python users, you should refer to the Python logging docs to configure the logger. :::
Use different loggers for different enforcers
Every enforcer can have its own logger to log information, and it can be changed at runtime.
And you can use a proper logger via the last parameter of NewEnforcer()
. If you are using this way to initialize your enforcer, you don't need to use the enabled parameter because the priority of the enabled field in the logger is higher.
// Définit un enregistreur par défaut en tant que enregistreur d'e1.
// This operation can also be seen as changing the logger of e1 at runtime.
e1.SetLogger(&Log.DefaultLogger{})
// Définit un autre enregistreur en tant que enregistreur de l'agent de sécurité e2.
e2.SetLogger(&YouOwnLogger)
// Set your logger when initializing enforcer e3.
e3, _ := casbin.NewEnforcer("examples/rbac_model.conf", a, logger)
Enregistreurs pris en charge
Nous fournissons des loggeurs pour vous aider à enregistrer des informations.
- Go
- PHP
Logger | Auteur | Description |
---|---|---|
Default logger (built-in) | Casbin | Le logger par défaut en utilisant le log golang. |
Zap logger | Casbin | Using zap, provide json encoded log and you can customize more with your own zap-logger. |
Logger | Auteur | Description |
---|---|---|
logger psr3-bridge | Casbin | Fournit un pont de connexion PSR-3. |
Comment écrire un logger
Votre logger devrait implémenter l'interface Logger.
Méthode | Type de texte | Description |
---|---|---|
EnableLog() | mandatory | Control whether to print the message. |
IsEnabled() | mandatory | Afficher le statut actif du logger. |
LogModel() | mandatory | Log info related to the model. |
LogEnforce() | mandatory | Log info related to enforcing. |
LogRole() | mandatory | Log info related to the role. |
Politique() de logg() | mandatory | Log info related to the policy. |
Vous pouvez passer votre log personnalisé
à Enforcer.SetLogger()
.
Here is an example of how to customize a logger for Golang:
import (
"fmt"
"log"
"strings"
)
// DefaultLogger est l'implémentation d'un Logger en utilisant le log golang.
type DefaultLogger struct {
enabled bool
}
func (l *DefaultLogger) EnableLog(enable bool) {
l. nabled = enable
}
func (l *DefaultLogger) IsEnabled() bool {
return l.enabled
}
func (l *DefaultLogger) LogModel(model [][]string) {
if !l. nabled {
return
}
var str strings.Builder
str. riteString("Modèle: ")
pour _, v := range model {
str. riteString(fmt.Sprintf("%v\n", v))
}
log.Println(str. tring())
}
func (l *DefaultLogger) LogEnforce(matcher string, request []interface{}, result bool, explains [][]string) {
if !l. {
return
}
var reqStr strings.Builder
reqStr. riteString("Requête: ")
pour i, rval := range request {
if i ! len(request)-1 {
reqStr. riteString(fmt. printf("%v, ", rval))
} else {
reqStr. riteString(fmt. printf("%v", rval))
}
}
reqStr. riteString(fmt.Sprintf(" ---> %t\n", résultat))
reqStr. riteString("Politique de frappe: ")
pour i, pval := intervalle explique {
si i ! len(expliques)-1 {
reqStr. riteString(fmt. printf("%v, ", pval))
} else {
reqStr. riteString(fmt. printf("%v \n", pval))
}
}
log. rintln(reqStr. tring())
}
func (l *DefaultLogger) LogPolicy(policy map[string][][]string) {
if !l. format@@0 nabled {
return
}
var str strings. uilder
str. riteString("Policy: ")
for k, v := range policy {
str.WriteString(fmt. printf("%s : %v\n", k, v))
}
log.Println(str. tring())
}
func (l *DefaultLogger) LogRole(roles []string) {
if !l. {
return
}
log.Println("Rôles : ", rôles)
}
Gestion des erreurs
Errors or panics may occur when you use Casbin for reasons like:
- Invalid syntax in the model file (.conf).
- Invalid syntax in the policy file (.csv).
- Custom errors from storage adapters, e.g., MySQL fails to connect.
- Casbin's bug.
There are five main functions you may need to be aware of for errors or panics:
Fonction | Comportement en cas d'erreur |
---|---|
NewEnforcer() | Returns an error |
format@@0 LoadModel() | Returns an error |
format@@0 LoadPolicy() | Returns an error |
EnregistrerPolicy() | Returns an error |
Forcer() | Returns an error |
NewEnforcer()
calls LoadModel()
and LoadPolicy()
internally. So you don't have to call the latter two when using NewEnforcer()
.
:::
Enable and disable
Le responsable peut être désactivé via la fonction Enforcer.EnableEnforce()
. Quand elle est désactivée, Enforcer.Enforce()
retournera toujours true
. Other operations like adding or removing policies are not affected. Voici un exemple :
e := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv")
// retournera false.
// Par défaut, le responsable est activé.
e.Enforce("non-authorized-user", "data1", "read")
// Disable the enforcer at runtime.
e.EnableEnforce(false)
// Renvoie vrai pour toute requête.
e.Enforce("non-authorized-user", "data1", "read")
// Activez le responsable à nouveau.
e.EnableEnforce(true)
// retournera false.
e.Enforce("non-autorised-user", "data1", "read")