golang reads the contents of the log file in the directory

PHPz
Release: 2024-02-05 23:51:07
forward
826 people have browsed it

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)
                }
        
            }
Copy after login


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()))
Copy after login

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
}) 
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template