A Prometheus logger implementation for Casbin, providing event-driven metrics collection for authorization events.
- Event-Driven Logging: Implements the Casbin Logger interface with support for event-driven logging
- Prometheus Metrics: Exports comprehensive metrics for Casbin operations
- Customizable Event Types: Filter which event types to log
- Custom Callbacks: Add custom processing for log entries
- Multiple Registries: Support for both default and custom Prometheus registries
casbin_enforce_total- Total number of enforce requests (labeled byallowed,domain)casbin_enforce_duration_seconds- Duration of enforce requests (labeled byallowed,domain)
casbin_policy_operations_total- Total number of policy operations (labeled byoperation,success)casbin_policy_operations_duration_seconds- Duration of policy operations (labeled byoperation)casbin_policy_rules_count- Number of policy rules affected by operations (labeled byoperation)
go get github.com/casbin/casbin-prometheus-loggerpackage main
import (
"net/http"
prometheuslogger "github.com/casbin/casbin-prometheus-logger"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
// Create logger with default Prometheus registry
logger := prometheuslogger.NewPrometheusLogger()
defer logger.Unregister()
// Or create with custom registry
registry := prometheus.NewRegistry()
logger := prometheuslogger.NewPrometheusLoggerWithRegistry(registry)
defer logger.UnregisterFrom(registry)
// Use with Casbin
// enforcer.SetLogger(logger)
// Expose metrics endpoint
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}// Only log specific event types
logger.SetEventTypes([]prometheuslogger.EventType{
prometheuslogger.EventEnforce,
prometheuslogger.EventAddPolicy,
})// Add custom processing for log entries
logger.SetLogCallback(func(entry *prometheuslogger.LogEntry) error {
fmt.Printf("Event: %s, Duration: %v\n", entry.EventType, entry.Duration)
return nil
})The logger supports the following event types:
EventEnforce- Authorization enforcement requestsEventAddPolicy- Policy addition operationsEventRemovePolicy- Policy removal operationsEventLoadPolicy- Policy loading operationsEventSavePolicy- Policy saving operations
This section guides you through setting up Prometheus and Grafana to visualize Casbin metrics.
-
Install Prometheus: Follow the official guide at https://prometheus.io/docs/introduction/first_steps/
-
Configure Prometheus to scrape metrics from your application. Edit your
prometheus.ymlconfiguration file and add a new job underscrape_configs:
scrape_configs:
- job_name: "casbin-prometheus-logger"
static_configs:
- targets: ["localhost:8080"]Replace localhost:8080 with the actual address where your application exposes the /metrics endpoint.
- Start Prometheus and verify it's scraping metrics by visiting
http://localhost:9090/targetsin your browser.
Follow the official Grafana installation guide at https://grafana.com/docs/grafana/latest/setup-grafana/installation/ for your platform. After installation, access Grafana via your browser (default: http://localhost:3000) and log in with the default credentials (admin/admin).
- In Grafana, navigate to Connections → Data Sources
- Click Add data source
- Select Prometheus
- Set the URL to your Prometheus endpoint (e.g.,
http://localhost:9090) - Click Save & Test to verify the connection
A pre-built Grafana dashboard is available for visualizing Casbin metrics. You can import the dashboard JSON file from grafana-dashboard.json.
To import the dashboard:
- In Grafana, go to Dashboards → Import
- Upload the
grafana-dashboard.jsonfile or paste its contents - Select the Prometheus data source you configured in the previous step
- Click Import
The dashboard includes the following panels organized into two sections:
- Total Enforce Rate - Overall rate of enforce requests per second
- Enforce Rate Detail (History) - Historical view broken down by allowed/denied status and domain
- Enforce Duration (Latency Distribution) - Histogram showing p50, p90, p95, and p99 latencies
- Enforce Duration by Status and Domain - Average duration broken down by status and domain
- Policy Operation Rate - Current rate of policy operations (Add/Save/Load/Remove)
- Policy Operations (Success/Failure) - Pie chart showing success vs failure distribution
- Policy Operation Rate History - Historical view of policy operations activity
- Policy Rules Affected History - Trend of the number of policy rules affected over time
- Policy Operation Duration (Latency Distribution) - Histogram showing p50, p90, and p99 latencies for policy operations
- Policy Operation Average Duration - Average duration by operation type
See the examples/basic directory for a complete working example.
To run the example:
cd examples/basic
go run main.goThen visit http://localhost:8080/metrics to see the exported metrics.
A long-running test simulates RBAC, ABAC, and ReBAC authorization patterns for testing with Prometheus and Grafana.
Note: This test is excluded from normal CI runs to avoid timeouts. It must be run manually with the longrunning build tag.
go test -v -tags longrunning -run TestLongRunning -timeout 0The test generates ~50-150 requests/second and exposes metrics on http://localhost:8080/metrics. Press Ctrl+C to stop.
- Start the test
- Configure Prometheus to scrape
localhost:8080/metrics - Import the Grafana dashboard from
grafana-dashboard.json
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
- Casbin - An authorization library that supports access control models
- Prometheus - Monitoring system and time series database
