Home >Backend Development >Golang >golang reads the contents of the log file in the directory

golang reads the contents of the log file in the directory

PHPz
PHPzforward
2024-02-05 23:51:07841browse

golang reads the contents of the log file in the directory

Question content

I am trying to read all log files within a directory, the code below is able to read the file names but not its contents .

Console output

ds-api-doc-.log false
2023/03/21 11:27:11 open /Users/xxx/ds-api-doc.log: no such file or directory 







 files, err := ioutil.ReadDir("./logs/")
            if err != nil {
                log.Fatal(err)
            }
            fmt.Println(totalTicks)
            for _, file := range files {
                fmt.Println(file.Name(), file.IsDir())
                abs, err := filepath.Abs(file.Name())
        
                file, err := os.Open(abs)
                if err != nil {
                    log.Fatal(err)
                }
                defer file.Close()
        
                scanner := bufio.NewScanner(file)
                for scanner.Scan() {
                    fmt.Println(scanner.Text())
                }
        
                if err := scanner.Err(); err != nil {
                    log.Fatal(err)
                }
        
            }

Correct answer


file.name() Returns only the base name of the file.

filepath.abs​​() will add the given path, in this case the base name of the file, to the current working directory. Therefore, the returned abs value will be missing the ./logs/ segment of the file path.

To resolve this issue, you can do the following:

abs, err := filepath.abs(filepath.join("logs", file.name()))

Alternatively, you can use filepath.walkdir, which provides the file path for the fn parameter.

err := filepath.WalkDir("./logs/", func(path string, de fs.DirEntry, err error) error) {
    if err != nil {
        return err
    } else if de.IsDir() {
        return nil
    }

    file, err := os.Open(path)
    // ...
    return nil
}) 

The above is the detailed content of golang reads the contents of the log file in the directory. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete