vitess.io/vitess@v0.16.2/go/vt/vttablet/filelogger/filelogger.go (about)

     1  /*
     2  Copyright 2019 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package filelogger implements an optional plugin that logs all queries to syslog.
    18  package filelogger
    19  
    20  import (
    21  	"github.com/spf13/pflag"
    22  
    23  	"vitess.io/vitess/go/streamlog"
    24  	"vitess.io/vitess/go/vt/log"
    25  	"vitess.io/vitess/go/vt/servenv"
    26  	"vitess.io/vitess/go/vt/vttablet/tabletserver/tabletenv"
    27  )
    28  
    29  var logQueriesToFile string
    30  
    31  func registerFlags(fs *pflag.FlagSet) {
    32  	// logQueriesToFile is the vttablet startup flag that must be set for this plugin to be active.
    33  	fs.StringVar(&logQueriesToFile, "log_queries_to_file", logQueriesToFile, "Enable query logging to the specified file")
    34  }
    35  
    36  func init() {
    37  	servenv.OnParseFor("vtcombo", registerFlags)
    38  	servenv.OnParseFor("vttablet", registerFlags)
    39  
    40  	servenv.OnRun(func() {
    41  		if logQueriesToFile != "" {
    42  			Init(logQueriesToFile)
    43  		}
    44  	})
    45  }
    46  
    47  // FileLogger is an opaque interface used to control the file logging
    48  type FileLogger interface {
    49  	// Stop logging to the given file
    50  	Stop()
    51  }
    52  
    53  type fileLogger struct {
    54  	logChan chan any
    55  }
    56  
    57  func (l *fileLogger) Stop() {
    58  	tabletenv.StatsLogger.Unsubscribe(l.logChan)
    59  }
    60  
    61  // Init starts logging to the given file path.
    62  func Init(path string) (FileLogger, error) {
    63  	log.Infof("Logging queries to file %s", path)
    64  	logChan, err := tabletenv.StatsLogger.LogToFile(path, streamlog.GetFormatter(tabletenv.StatsLogger))
    65  	if err != nil {
    66  		return nil, err
    67  	}
    68  	return &fileLogger{
    69  		logChan: logChan,
    70  	}, nil
    71  }