github.com/jkawamoto/roadie-azure@v0.3.5/roadie/logger.go (about)

     1  //
     2  // roadie/logger.go
     3  //
     4  // Copyright (c) 2017 Junpei Kawamoto
     5  //
     6  // This file is part of Roadie Azure.
     7  //
     8  // Roadie Azure is free software: you can redistribute it and/or modify
     9  // it under the terms of the GNU General Public License as published by
    10  // the Free Software Foundation, either version 3 of the License, or
    11  // (at your option) any later version.
    12  //
    13  // Roadie Azure is distributed in the hope that it will be useful,
    14  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    15  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    16  // GNU General Public License for more details.
    17  //
    18  // You should have received a copy of the GNU General Public License
    19  // along with Roadie Azure. If not, see <http://www.gnu.org/licenses/>.
    20  //
    21  
    22  package roadie
    23  
    24  import (
    25  	"context"
    26  	"fmt"
    27  	"io"
    28  
    29  	"github.com/Azure/azure-sdk-for-go/storage"
    30  	"github.com/jkawamoto/roadie/cloud/azure"
    31  )
    32  
    33  // pipedWriter is a WriterClose which uploads written messages to a cloud storage.
    34  type pipedWriter struct {
    35  	io.WriteCloser
    36  	done chan struct{}
    37  }
    38  
    39  // Close this writer.
    40  func (w *pipedWriter) Close() (err error) {
    41  	err = w.WriteCloser.Close()
    42  	<-w.done
    43  	return
    44  }
    45  
    46  // NewLogWriter creates a new writer which writes messages to a given named
    47  // file in the cloud storage.
    48  func NewLogWriter(ctx context.Context, store *azure.StorageService, name string, debug io.Writer) (writer io.WriteCloser) {
    49  
    50  	reader, writer := io.Pipe()
    51  	done := make(chan struct{}, 1)
    52  
    53  	go func() {
    54  		defer reader.Close()
    55  		err := store.UploadWithMetadata(ctx, azure.LogContainer, name, reader, &storage.BlobProperties{
    56  			ContentType: "text/plain",
    57  		}, nil)
    58  		if err != nil {
    59  			if debug != nil {
    60  				fmt.Fprintln(debug, err.Error())
    61  			}
    62  		}
    63  		close(done)
    64  	}()
    65  
    66  	return &pipedWriter{
    67  		WriteCloser: writer,
    68  		done:        done,
    69  	}
    70  
    71  }