A Bark logging handler logging output to a named file.  If the
    file has changed since the last log message was written, it will
    be closed and reopened.

    Similar to logging.handlers.WatchedFileHandler.
3039
def watched_file_handler(name, logname, filename, mode='a', encoding=None,
                         delay=False):
    

    return wrap_log_handler(logging.handlers.WatchedFileHandler(
        filename, mode=mode, encoding=encoding, delay=delay))
935190
def log_to_file(filename, level=DEBUG):
    """"""
    l = logging.getLogger("paramiko")
    if len(l.handlers) > 0:
        return
    l.setLevel(level)
    f = open(filename, 'w')
    lh = logging.StreamHandler(f)
    lh.setFormatter(logging.Formatter('%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(_threadid)-3d %(name)s: %(message)s',
                                      '%Y%m%d-%H:%M:%S'))
    l.addHandler(lh)
464461
def _logger_stream(self):
        """"""
        sh = logging.StreamHandler()
        sh.set_name('sh')
        sh.setLevel(logging.INFO)
        sh.setFormatter(self._logger_formatter)
        self.log.addHandler(sh)
400722
function Watch_file(that,          // @arg this
                    watchFilePath, // @arg String   - watch file path
                    callback) {    // @arg Function - callback(null):void
    var timerID = 0;

    if (this._options.verbose) {
        console.log("  file: " + watchFilePath);
    }

    fs.watchFile(watchFilePath, _watchdogCallback);

    function _watchdogCallback() {
        if (timerID) {
            clearTimeout(timerID); timerID = 0;
        }
        timerID = setTimeout(function() {
            clearTimeout(timerID); timerID = 0;

            callback(null);
        }, that._options.delay);
    }
}
46147
def _get_file_event_handler(self, file_path, save_name):
        
        self._file_pusher.update_file(save_name, file_path)  # track upload progress

        if save_name not in self._file_event_handlers:
            if save_name == 'wandb-history.jsonl':
                self._file_event_handlers['wandb-history.jsonl'] = FileEventHandlerTextStream(
                    file_path, 'wandb-history.jsonl', self._api)
            elif save_name == 'wandb-events.jsonl':
                self._file_event_handlers['wandb-events.jsonl'] = FileEventHandlerTextStream(
                    file_path, 'wandb-events.jsonl', self._api)
            elif 'tfevents' in save_name or 'graph.pbtxt' in save_name:
                # overwrite the tensorboard but not every reload -- just
                # frequently enough to resemble realtime
                self._file_event_handlers[save_name] = FileEventHandlerThrottledOverwrite(
                    file_path, save_name, self._api, self._file_pusher)
            # Don't try to stream tensorboard files for now.
            # elif 'tfevents' in save_name:
            #    # TODO: This is hard-coded, but we want to give users control
            #    # over streaming files (or detect them).
            #    self._api.get_file_stream_api().set_file_policy(save_name,
            #                                                    BinaryFilePolicy())
            #    self._file_event_handlers[save_name] = FileEventHandlerBinaryStream(
            #        file_path, save_name, self._api)
            # Overwrite handler (non-deferred) has a bug, wherein if the file is truncated
            # during upload, the request to Google hangs (at least, this is my working
            # theory). So for now we defer uploading everything til the end of the run.
            # TODO: send wandb-summary during run. One option is to copy to a temporary
            # file before uploading.
            elif save_name == config.FNAME:
                self._file_event_handlers[save_name] = FileEventHandlerConfig(
                    file_path, save_name, self._api, self._file_pusher, self._run)
            elif save_name == 'wandb-summary.json':
                # Load the summary into the syncer process for meta etc to work
                self._run.summary.load()
                self._api.get_file_stream_api().set_file_policy(save_name, OverwriteFilePolicy())
                self._file_event_handlers[save_name] = FileEventHandlerSummary(
                    file_path, save_name, self._api, self._file_pusher, self._run)
            elif save_name.startswith('media/'):
                # Save media files immediately
                self._file_event_handlers[save_name] = FileEventHandlerOverwrite(
                    file_path, save_name, self._api, self._file_pusher)
            else:
                Handler = FileEventHandlerOverwriteDeferred
                for policy, globs in six.iteritems(self._user_file_policies):
                    if policy == "end":
                        continue
                    for g in globs:
                        if any(save_name in p for p in glob.glob(os.path.join(self._run.dir, g))):
                            if policy == "live":
                                Handler = FileEventHandlerThrottledOverwriteMinWait
                self._file_event_handlers[save_name] = Handler(
                    file_path, save_name, self._api, self._file_pusher)
        return self._file_event_handlers[save_name]
458751
def __log(self, method_name):
        
        if not self.__already_logged:
            # Print only if not already done
            stack = "\n\t".join(traceback.format_stack())

            logging.getLogger(self.__logger).warning(
                "%s: %s\n%s", method_name, self.__message, stack
            )
            self.__already_logged = True
321720
def _handle_dump(self, handler, file_object, **kwargs):
    

    return handler.dump(self.__class__, to_dict(self), file_object, **kwargs)
836214
def logToFile(path, level=logging.INFO):
    
    logger = logging.getLogger()
    logger.setLevel(level)
    formatter = logging.Formatter(
        '%(asctime)s %(name)s %(levelname)s %(message)s')
    handler = logging.FileHandler(path)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
628083
def capture_logger(name):
    
    import logging

    logger = logging.getLogger(name)
    try:
        import StringIO
        stream = StringIO.StringIO()
    except ImportError:
        from io import StringIO
        stream = StringIO()
    handler = logging.StreamHandler(stream)
    logger.addHandler(handler)
    try:
        yield stream
    finally:
        logger.removeHandler(handler)
171994
def get_logfile(logger=None):
    
    logger = logger or logging.getLogger()
    handlers = [i for i in logger.handlers if isinstance(i, logging.FileHandler)]
    return handlers[0].baseFilename if handlers else None
232203
protected void closeFile() {
	if (this.qw != null) {
	    try {
		this.qw.close();
	    }
	    catch (java.io.IOException e) {
		// Exceptionally, it does not make sense to delegate to an
		// ErrorHandler. Since a closed appender is basically dead.
		LogLog.error("Could not close " + qw, e);
	    }
	}
    }
220994
def setup_file_logger(filename, formatting, log_level):
    
    logger = logging.getLogger()
    # If a stream handler has been attached, remove it.
    if logger.handlers:
        logger.removeHandler(logger.handlers[0])
    handler = logging.FileHandler(filename)
    logger.addHandler(handler)
    formatter = logging.Formatter(*formatting)
    handler.setFormatter(formatter)
    logger.setLevel(log_level)
    handler.setLevel(log_level)
    return logger
1090099
def start_file_logger(self, name, log_file_level=logging.DEBUG, log_file_path='./'):
        """"""

        log_file_path = os.path.expanduser(log_file_path) / '{}.log'.format(name)
        logdir = log_file_path.parent

        try:
            logdir.mkdir(parents=True, exist_ok=True)

            # If the log file exists, backs it up before creating a new file handler
            if log_file_path.exists():
                strtime = datetime.datetime.utcnow().strftime('%Y-%m-%d_%H:%M:%S')
                shutil.move(log_file_path, log_file_path + '.' + strtime)

            self.fh = TimedRotatingFileHandler(str(log_file_path), when='midnight', utc=True)
            self.fh.suffix = '%Y-%m-%d_%H:%M:%S'
        except (IOError, OSError) as ee:
            warnings.warn('log file {0!r} could not be opened for writing: '
                          '{1}'.format(log_file_path, ee), RuntimeWarning)
        else:
            self.fh.setFormatter(fmt)
            self.addHandler(self.fh)
            self.fh.setLevel(log_file_level)

        self.log_filename = log_file_path
1233596
public void read(final String filename, final AsyncResultHandler<String> handler) {
        isFresh(filename, new Handler<Boolean>() {
            @Override
            public void handle(Boolean fresh) {
                if (fresh) {
                    String cachedValue = getFileFromCache(filename);
                    if (cachedValue != null) {
                        handler.handle(new YokeAsyncResult<>(null, cachedValue));
                        return;
                    }
                }
                // either fresh is false or cachedValue is null
                loadToCache(filename, new Handler<Throwable>() {
                    @Override
                    public void handle(Throwable error) {
                        if (error != null) {
                            handler.handle(new YokeAsyncResult<String>(error, null));
                            return;
                        }
                        // no error
                        handler.handle(new YokeAsyncResult<>(null, getFileFromCache(filename)));
                    }
                });
            }
        });
    }
1041682
def get_logger(name):
    

    log = logging.getLogger(name)
    if not log.handlers:
        log.addHandler(NullHandler())
    return log
288639
def set_log_rotate_handler(self, set_file):
        '''

        '''
        if hasattr(self, 'debug_handler'):
            if set_file:
                self.log.addHandler(self.debug_handler)
                self.log.addHandler(self.error_handler)
            else:
                try:
                    self.log.removeHandler(self.error_handler)
                    self.log.removeHandler(self.debug_handler)
                except Exception:
                    pass
        else:
            self.log.debug('The file log handlers were not created. It is not\
                           possible to write to the log files.')
1141479
def get_logger(name, file_name=None, stream=None, template=None, propagate=False, level=None):
    

    logger = logging.getLogger(name)
    running_tests = (
        'test' in sys.argv  # running with setup.py
        or sys.argv[0].endswith('py.test'))  # running with py.test
    if running_tests and not level:
        # testing without level, this means tester does not want to see any log messages.
        level = logging.CRITICAL

    if not level:
        level = logging.INFO
    logger.setLevel(level)
    logger.propagate = propagate

    formatter = logging.Formatter(template)

    if not stream:
        stream = sys.stdout

    logger.handlers = []
    handler = logging.StreamHandler(stream=stream)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    if file_name:
        handler = logging.FileHandler(file_name)
        handler.setFormatter(logging.Formatter('%(asctime)s '+template))
        logger.addHandler(handler)

    return logger