trpc.group/trpc-go/trpc-go@v1.0.3/log/rollwriter/roll_writer_unix.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  //go:build !windows
    15  // +build !windows
    16  
    17  package rollwriter
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"sync/atomic"
    23  	"time"
    24  )
    25  
    26  // doReopenFile reopens the file.
    27  func (w *RollWriter) doReopenFile(path, _ string) error {
    28  	atomic.StoreInt64(&w.openTime, time.Now().Unix())
    29  	f, err := w.os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
    30  	if err != nil {
    31  		return fmt.Errorf("os.OpenFile %s err: %w", path, err)
    32  	}
    33  	last := w.getCurrFile()
    34  	w.setCurrFile(f)
    35  	if last != nil {
    36  		w.delayCloseAndRenameFile(&closeAndRenameFile{file: last})
    37  	}
    38  	st, err := w.os.Stat(path)
    39  	if err != nil {
    40  		return fmt.Errorf("os.Stat %s err: %w", path, err)
    41  	}
    42  	atomic.StoreInt64(&w.currSize, st.Size())
    43  	return nil
    44  }
    45  
    46  // backupFile backs this file up and reopen a new one if file size is too large.
    47  func (w *RollWriter) backupFile() {
    48  	if !(w.opts.MaxSize > 0 && atomic.LoadInt64(&w.currSize) >= w.opts.MaxSize) {
    49  		return
    50  	}
    51  	atomic.StoreInt64(&w.currSize, 0)
    52  
    53  	// Rename the old file.
    54  	backup := w.currPath + "." + time.Now().Format(backupTimeFormat)
    55  	if _, err := w.os.Stat(w.currPath); !os.IsNotExist(err) {
    56  		if err := w.os.Rename(w.currPath, backup); err != nil {
    57  			fmt.Printf("os.Rename from %s to backup %s err: %+v\n", w.currPath, backup, err)
    58  		}
    59  	}
    60  
    61  	// Reopen a new one.
    62  	if err := w.doReopenFile(w.currPath, ""); err != nil {
    63  		fmt.Printf("w.doReopenFile %s err: %+v\n", w.currPath, err)
    64  	}
    65  	w.notify()
    66  }