prometheuslogger

package module
v1.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 9, 2026 License: Apache-2.0 Imports: 2 Imported by: 0

Image README

casbin-prometheus-logger

Go Report Card Go Coverage Status GoDoc Release Discord

A Prometheus logger implementation for Casbin, providing event-driven metrics collection for authorization events.

grafana

Features

  • 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

Metrics Exported

Enforce Metrics
  • casbin_enforce_total - Total number of enforce requests (labeled by allowed, domain)
  • casbin_enforce_duration_seconds - Duration of enforce requests (labeled by allowed, domain)
Policy Operation Metrics
  • casbin_policy_operations_total - Total number of policy operations (labeled by operation, success)
  • casbin_policy_operations_duration_seconds - Duration of policy operations (labeled by operation)
  • casbin_policy_rules_count - Number of policy rules affected by operations (labeled by operation)

Installation

go get github.com/casbin/casbin-prometheus-logger

Usage

Basic Usage
package 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)
}
Configure Event Types
// Only log specific event types
logger.SetEventTypes([]prometheuslogger.EventType{
    prometheuslogger.EventEnforce,
    prometheuslogger.EventAddPolicy,
})
Add Custom Callback
// 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
})

Event Types

The logger supports the following event types:

  • EventEnforce - Authorization enforcement requests
  • EventAddPolicy - Policy addition operations
  • EventRemovePolicy - Policy removal operations
  • EventLoadPolicy - Policy loading operations
  • EventSavePolicy - Policy saving operations

Prometheus + Grafana Setup

This section guides you through setting up Prometheus and Grafana to visualize Casbin metrics.

1. Install and Configure Prometheus
  1. Install Prometheus: Follow the official guide at https://prometheus.io/docs/introduction/first_steps/

  2. Configure Prometheus to scrape metrics from your application. Edit your prometheus.yml configuration file and add a new job under scrape_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.

  1. Start Prometheus and verify it's scraping metrics by visiting http://localhost:9090/targets in your browser.
2. Install Grafana

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).

3. Configure Grafana Data Source
  1. In Grafana, navigate to ConnectionsData Sources
  2. Click Add data source
  3. Select Prometheus
  4. Set the URL to your Prometheus endpoint (e.g., http://localhost:9090)
  5. Click Save & Test to verify the connection
4. Import Casbin Dashboard

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:

  1. In Grafana, go to DashboardsImport
  2. Upload the grafana-dashboard.json file or paste its contents
  3. Select the Prometheus data source you configured in the previous step
  4. Click Import
Dashboard Panels

The dashboard includes the following panels organized into two sections:

Enforce Metrics
  • 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 Metrics
  • 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

Example

See the examples/basic directory for a complete working example.

To run the example:

cd examples/basic
go run main.go

Then visit http://localhost:8080/metrics to see the exported metrics.

Long-Running Test

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.

Usage
go test -v -tags longrunning -run TestLongRunning -timeout 0

The test generates ~50-150 requests/second and exposes metrics on http://localhost:8080/metrics. Press Ctrl+C to stop.

Integration with Prometheus/Grafana
  1. Start the test
  2. Configure Prometheus to scrape localhost:8080/metrics
  3. Import the Grafana dashboard from grafana-dashboard.json

License

This project is licensed under the Apache 2.0 License - see the LICENSE file for details.

Contributing

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

Image Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type EventType

type EventType string

EventType represents the type of logging event. These types are defined to match the casbin/v2/log package interface.

const (
	EventEnforce      EventType = "enforce"
	EventAddPolicy    EventType = "addPolicy"
	EventRemovePolicy EventType = "removePolicy"
	EventLoadPolicy   EventType = "loadPolicy"
	EventSavePolicy   EventType = "savePolicy"
)

Event type constants.

type LogEntry

type LogEntry struct {
	IsActive bool
	// EventType is the type of the event being logged.
	EventType EventType

	StartTime time.Time
	EndTime   time.Time
	Duration  time.Duration

	// Enforce parameters.
	// Subject is the user or entity requesting access.
	Subject string
	// Object is the resource being accessed.
	Object string
	// Action is the operation being performed.
	Action string
	// Domain is the domain/tenant for multi-tenant scenarios.
	Domain string
	// Allowed indicates whether the enforcement request was allowed.
	Allowed bool

	// Rules contains the policy rules involved in the operation.
	Rules [][]string
	// RuleCount is the number of rules affected by the operation.
	RuleCount int

	// Error contains any error that occurred during the event.
	Error error
}

LogEntry represents a complete log entry for a Casbin event. This type is defined to match the casbin/v2/log package interface.

type Logger

type Logger interface {
	SetEventTypes([]EventType) error
	// OnBeforeEvent is called before an event occurs and returns a handle for context.
	OnBeforeEvent(entry *LogEntry) error
	// OnAfterEvent is called after an event completes with the handle and final entry.
	OnAfterEvent(entry *LogEntry) error

	SetLogCallback(func(entry *LogEntry) error) error
}

Logger defines the interface for event-driven logging in Casbin. This interface is defined to match the casbin/v2/log package interface.

type PrometheusLogger

type PrometheusLogger struct {
	// contains filtered or unexported fields
}

PrometheusLogger is a logger that exports metrics to Prometheus.

func NewPrometheusLogger

func NewPrometheusLogger() *PrometheusLogger

NewPrometheusLogger creates a new PrometheusLogger with default metrics.

func NewPrometheusLoggerWithRegistry

func NewPrometheusLoggerWithRegistry(registry *prometheus.Registry) *PrometheusLogger

NewPrometheusLoggerWithRegistry creates a new PrometheusLogger with a custom registry.

func (*PrometheusLogger) GetEnforceDuration

func (p *PrometheusLogger) GetEnforceDuration() *prometheus.HistogramVec

GetEnforceDuration returns the enforce duration histogram metric.

func (*PrometheusLogger) GetEnforceTotal

func (p *PrometheusLogger) GetEnforceTotal() *prometheus.CounterVec

GetEnforceTotal returns the enforce total counter metric.

func (*PrometheusLogger) GetPolicyOpsDuration

func (p *PrometheusLogger) GetPolicyOpsDuration() *prometheus.HistogramVec

GetPolicyOpsDuration returns the policy operations duration histogram metric.

func (*PrometheusLogger) GetPolicyOpsTotal

func (p *PrometheusLogger) GetPolicyOpsTotal() *prometheus.CounterVec

GetPolicyOpsTotal returns the policy operations total counter metric.

func (*PrometheusLogger) GetPolicyRulesCount

func (p *PrometheusLogger) GetPolicyRulesCount() *prometheus.GaugeVec

GetPolicyRulesCount returns the policy rules count gauge metric.

func (*PrometheusLogger) OnAfterEvent

func (p *PrometheusLogger) OnAfterEvent(entry *LogEntry) error

OnAfterEvent is called after an event completes and records metrics.

func (*PrometheusLogger) OnBeforeEvent

func (p *PrometheusLogger) OnBeforeEvent(entry *LogEntry) error

OnBeforeEvent is called before an event occurs.

func (*PrometheusLogger) SetEventTypes

func (p *PrometheusLogger) SetEventTypes(eventTypes []EventType) error

SetEventTypes configures which event types should be logged.

func (*PrometheusLogger) SetLogCallback

func (p *PrometheusLogger) SetLogCallback(callback func(entry *LogEntry) error) error

SetLogCallback sets a custom callback function for log entries.

func (*PrometheusLogger) Unregister

func (p *PrometheusLogger) Unregister()

Unregister unregisters all metrics from the default Prometheus registry. This is useful for testing or when you need to recreate the logger.

func (*PrometheusLogger) UnregisterFrom

func (p *PrometheusLogger) UnregisterFrom(registry *prometheus.Registry) bool

UnregisterFrom unregisters all metrics from a specific Prometheus registry.

Image Directories

Path Synopsis
examples
basic command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL