Changeset 247 in code for trunk


Ignore:
Timestamp:
Apr 7, 2020, 7:50:12 PM (5 years ago)
Author:
contact
Message:

Extract logic to build log filepath into a function

This will get re-used when parsing logs.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/logger.go

    r235 r247  
    1515        entity string
    1616
    17         filename string
    18         file     *os.File
     17        path string
     18        file *os.File
    1919}
    2020
     
    2424                entity: entity,
    2525        }
     26}
     27
     28func logPath(network *network, entity string, t time.Time) string {
     29        user := network.user
     30        srv := user.srv
     31
     32        // TODO: handle/forbid network/entity names with illegal path characters
     33        year, month, day := t.Date()
     34        filename := fmt.Sprintf("%04d-%02d-%02d.log", year, month, day)
     35        return filepath.Join(srv.LogPath, user.Username, network.GetName(), entity, filename)
    2636}
    2737
     
    3747        // TODO: handle non-monotonic clock behaviour
    3848        now := time.Now()
    39         year, month, day := now.Date()
    40         filename := fmt.Sprintf("%04d-%02d-%02d.log", year, month, day)
    41         if ml.filename != filename {
     49        path := logPath(ml.conn.network, ml.entity, now)
     50        if ml.path != path {
    4251                if ml.file != nil {
    4352                        ml.file.Close()
    4453                }
    4554
    46                 // TODO: handle/forbid network/entity names with illegal path characters
    47                 dir := filepath.Join(ml.conn.srv.LogPath, ml.conn.user.Username, ml.conn.network.GetName(), ml.entity)
     55                dir := filepath.Dir(path)
    4856                if err := os.MkdirAll(dir, 0700); err != nil {
    4957                        return fmt.Errorf("failed to create logs directory %q: %v", dir, err)
    5058                }
    5159
    52                 path := filepath.Join(dir, filename)
    5360                f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
    5461                if err != nil {
     
    5663                }
    5764
    58                 ml.filename = filename
     65                ml.path = path
    5966                ml.file = f
    6067        }
     
    6269        _, err := fmt.Fprintf(ml.file, "[%02d:%02d:%02d] %s\n", now.Hour(), now.Minute(), now.Second(), s)
    6370        if err != nil {
    64                 return fmt.Errorf("failed to log message to %q: %v", ml.filename, err)
     71                return fmt.Errorf("failed to log message to %q: %v", ml.path, err)
    6572        }
    6673        return nil
Note: See TracChangeset for help on using the changeset viewer.