Through the first four days , We have basically realized docker The core function of , A few days later , I’m going to bring you some docker Other orders for , Today we mainly come to realize docker logs function , That is to see docker Internal log
Write the log
Let’s talk about the general idea , This feature is actually relatively simple , To put it bluntly , Go to the console output , Now it’s better to output to the file , We go through
docker logs
Check the log , That is to open the file , Show the contents of the file
Start transforming
We will
tty
Pass to create the parent thread where it isprocess.go
Of NewParentProcess function ,tty That is to say-ti
Parameters , That is to start in command line interaction mode , If the user doesn’t type-ti
, Then I will output the log information to the file , Here we’ll take the container of Name As the file name , It is convenient for us to directly query the logs in the container through the container name .
func NewParentProcess(tty bool, volume, containerName, imageName string, envs []string) (*exec.Cmd, *os.File) {
// .....
if tty {
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
} else {
// Output the log to a file
logDir := path.Join(common.DefaultContainerInfoPath, containerName)
if _, err := os.Stat(logDir); err != nil && os.IsNotExist(err) {
err := os.MkdirAll(logDir, os.ModePerm)
if err != nil {
logrus.Errorf("mkdir container log, err: %v", err)
}
}
logFileName := path.Join(logDir, common.ContainerLogFileName)
file, err := os.Create(logFileName)
if err != nil {
logrus.Errorf("create log file, err: %v", err)
}
// take cmd The output stream of is changed to the file stream
cmd.Stdout = file
}
}
Check the log
Add a new one command Command parameter :
logs
var logCommand = cli.Command{
Name: "logs",
Usage: "look container log",
Action: func(ctx *cli.Context) error {
if len(ctx.Args()) < 1 {
return fmt.Errorf("missing container name")
}
containerName := ctx.Args().Get(0)
container.LookContainerLog(containerName)
return nil
},
}
to glance at LookContainerLog
The concrete realization of , It’s about reading documents …
// View the log information in the container
func LookContainerLog(containerName string) {
logFileName := path.Join(common.DefaultContainerInfoPath, containerName, common.ContainerLogFileName)
file, err := os.Open(logFileName)
if err != nil {
logrus.Errorf("open log file, path: %s, err: %v", logFileName, err)
}
bs, err := ioutil.ReadAll(file)
if err != nil {
logrus.Errorf("read log file, err: %v", err)
}
_, _ = fmt.Fprint(os.Stdout, string(bs))
}