github.com/ztalab/ZACA@v0.0.1/pkg/logger/redis_hook/redis_hook.go (about)

     1  package redis_hook
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/garyburd/redigo/redis"
     6  	"time"
     7  )
     8  
     9  // HookConfig stores configuration needed to setup the hook
    10  type HookConfig struct {
    11  	Key      string
    12  	Host     string
    13  	Password string
    14  	Port     int
    15  	TTL      int
    16  }
    17  
    18  // RedisHook to sends logs to Redis server
    19  type RedisHook struct {
    20  	RedisPool      *redis.Pool
    21  	RedisHost      string
    22  	RedisKey       string
    23  	LogstashFormat string
    24  	AppName        string
    25  	Hostname       string
    26  	RedisPort      int
    27  	TTL            int
    28  }
    29  
    30  // NewHook creates a hook to be added to an instance of logger
    31  func NewHook(config HookConfig) (redisHook *RedisHook, err error) {
    32  	pool := newRedisConnectionPool(config.Host, config.Password, config.Port, 0)
    33  
    34  	// test if connection with REDIS can be established
    35  	conn := pool.Get()
    36  	defer conn.Close()
    37  
    38  	// check connection
    39  	_, err = conn.Do("PING")
    40  	if err != nil {
    41  		err = fmt.Errorf("unable to connect to REDIS: %s", err)
    42  	}
    43  	redisHook = &RedisHook{
    44  		RedisHost:      config.Host,
    45  		RedisPool:      pool,
    46  		RedisKey:       config.Key,
    47  		LogstashFormat: "origin",
    48  		TTL:            config.TTL,
    49  	}
    50  	return
    51  }
    52  
    53  func newRedisConnectionPool(server, password string, port int, db int) *redis.Pool {
    54  	hostPort := fmt.Sprintf("%s:%d", server, port)
    55  	return &redis.Pool{
    56  		MaxIdle:     3,
    57  		IdleTimeout: 240 * time.Second,
    58  		Dial: func() (redis.Conn, error) {
    59  			c, err := redis.Dial("tcp", hostPort, redis.DialDatabase(db),
    60  				redis.DialPassword(password),
    61  				redis.DialConnectTimeout(time.Second),
    62  				redis.DialReadTimeout(time.Millisecond*100),
    63  				redis.DialWriteTimeout(time.Millisecond*100))
    64  			if err != nil {
    65  				return nil, err
    66  			}
    67  			return c, err
    68  		},
    69  		TestOnBorrow: func(c redis.Conn, t time.Time) error {
    70  			_, err := c.Do("PING")
    71  			return err
    72  		},
    73  	}
    74  }