Write memcache debug info to the log
165400
protected function debug($type, $key, $data = null, $result = null)
    {
        $line = strtoupper($type) . ' ' . $key;

        if ($data !== null) {
            $line .= ' ' . $data;
        }

        rcube::debug('memcache', $line, $result);
    }
374952
private String write(String logDir) throws IOException, ExecutionException, InterruptedException {
        final File file = new File(logDir, "trace_" + System.currentTimeMillis() + ".json.gz");
        if (file.exists()) {
            throw new IOException("Trace file " + file.getAbsolutePath() + " already exists");
        }
        if (!file.getParentFile().canWrite() || !file.getParentFile().canExecute()) {
            throw new IOException("Trace file " + file.getAbsolutePath() + " is not writable");
        }

        SettableFuture<Future<?>> f = SettableFuture.create();
        m_work.offer(() -> f.set(dumpEvents(file)));
        final Future<?> writeFuture = f.get();
        if (writeFuture != null) {
            writeFuture.get(); // Wait for the write to finish without blocking new events
            return file.getAbsolutePath();
        } else {
            // A write is already in progress, ignore this request
            return null;
        }
    }
139780
def write(self):
        
        io.debug("Storing cache '{0}'".format(self.path))
        with open(self.path, "w") as file:
            json.dump(self._data, file, sort_keys=True, indent=2,
                      separators=(',', ': '))
182835
private void handleWrites(final MemcachedNode node) throws IOException {
    node.fillWriteBuffer(shouldOptimize);
    boolean canWriteMore = node.getBytesRemainingToWrite() > 0;
    while (canWriteMore) {
      int wrote = node.writeSome();
      metrics.updateHistogram(OVERALL_AVG_BYTES_WRITE_METRIC, wrote);
      node.fillWriteBuffer(shouldOptimize);
      canWriteMore = wrote > 0 && node.getBytesRemainingToWrite() > 0;
    }
  }
513391
public static void infoAndDebug(Logger log, String methodName,
            Object... params) {
        if (!log.isInfoEnabled())
            return;
        int length = params.length;
        Object[] newParams = new Object[length];
        boolean hasCollection = false;
        for (int i = 0; i < length; i++) {
            if (params[i] instanceof Collection) {
                newParams[i] = (((Collection<?>) params[i]).size());
                hasCollection = true;
            } else
                newParams[i] = params[i];
        }
        if (hasCollection)
            log.info(buildMethodLogString(methodName, newParams));
        log.debug(buildMethodLogString(methodName, params));
    }
874301
def dtool(debug):
    """"""
    level = logging.WARNING
    if debug:
        level = logging.DEBUG
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=level)
911869
def cache(self):
      """"""
      msg = 'Saving updates from more recent "%s" to "%s"'
      log.info(msg, self.filename, self.cachename)
      with open(self.cachename, 'wb') as output:
          cPickle.dump(self._dict, output, -1)
181556
def dump(self, cache_file=None):
        """"""
        if cache_file is None:
            cache_file = self.cache_file
        if cache_file is not None:
            self.cache_file = cache_file
            with open(cache_file, 'wb') as pickle_fh:
                pickle.dump(
                    (self.remote, self.backend.name, self.max_sleep_interval,
                     self.job_id, self._status, self.epilogue, self.ssh,
                     self.scp),
                    pickle_fh)
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)
117581
public static function load()
    {
        if (!extension_loaded('opencensus')) {
            trigger_error('opencensus extension required to load Memcached integrations.', E_USER_WARNING);
            return;
        }

        // bool Memcached::add ( string $key , mixed $value [, int $expiration ] )
        opencensus_trace_method('Memcached', 'add', [self::class, 'handleAttributes']);

        // bool Memcached::addByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
        opencensus_trace_method('Memcached', 'addByKey', [self::class, 'handleAttributesByKey']);

        // bool Memcached::append ( string $key , string $value )
        opencensus_trace_method('Memcached', 'append', [self::class, 'handleAttributes']);

        // bool Memcached::appendByKey ( string $server_key , string $key , string $value )
        opencensus_trace_method('Memcached', 'appendByKey', [self::class, 'handleAttributesByKey']);

        // bool Memcached::cas ( float $cas_token , string $key , mixed $value [, int $expiration ] )
        opencensus_trace_method('Memcached', 'cas', [self::class, 'handleCas']);

        // bool Memcached::casByKey ( float $cas_token , string $server_key , string $key , mixed $value
        //                            [, int $expiration ] )
        opencensus_trace_method('Memcached', 'casByKey', [self::class, 'handleCasByKey']);

        // int Memcached::decrement ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )
        opencensus_trace_method('Memcached', 'decrement', [self::class, 'handleAttributes']);

        // int Memcached::decrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0
        //                                 [, int $expiry = 0 ]]] )
        opencensus_trace_method('Memcached', 'decrementByKey', [self::class, 'handleAttributesByKey']);

        // bool Memcached::delete ( string $key [, int $time = 0 ] )
        opencensus_trace_method('Memcached', 'delete', [self::class, 'handleAttributes']);

        // bool Memcached::deleteByKey ( string $server_key , string $key [, int $time = 0 ] )
        opencensus_trace_method('Memcached', 'deleteByKey', [self::class, 'handleAttributesByKey']);

        // bool Memcached::flush ([ int $delay = 0 ] )
        opencensus_trace_method('Memcached', 'flush');

        // mixed Memcached::get ( string $key [, callable $cache_cb [, int &$flags ]] )
        opencensus_trace_method('Memcached', 'get', [self::class, 'handleAttributes']);

        // mixed Memcached::getByKey ( string $server_key , string $key [, callable $cache_cb [, int $flags ]] )
        opencensus_trace_method('Memcached', 'getByKey', [self::class, 'handleAttributesByKey']);

        // mixed Memcached::getMulti ( array $keys [, int $flags ] )
        opencensus_trace_method('Memcached', 'getMulti', [self::class, 'handleAttributes']);

        // array Memcached::getMultiByKey ( string $server_key , array $keys [, int $flags ] )
        opencensus_trace_method('Memcached', 'getMultiByKey', [self::class, 'handleAttributesByKey']);

        // int Memcached::increment ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] )
        opencensus_trace_method('Memcached', 'increment', [self::class, 'handleAttributes']);

        // int Memcached::incrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0
        //                                 [, int $expiry = 0 ]]] )
        opencensus_trace_method('Memcached', 'incrementByKey', [self::class, 'handleAttributesByKey']);

        // bool Memcached::prepend ( string $key , string $value )
        opencensus_trace_method('Memcached', 'prepend', [self::class, 'handleAttributes']);

        // bool Memcached::prependByKey ( string $server_key , string $key , string $value )
        opencensus_trace_method('Memcached', 'prependByKey', [self::class, 'handleAttributesByKey']);

        // bool Memcached::replace ( string $key , mixed $value [, int $expiration ] )
        opencensus_trace_method('Memcached', 'replace', [self::class, 'handleAttributes']);

        // bool Memcached::replaceByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
        opencensus_trace_method('Memcached', 'replaceByKey', [self::class, 'handleAttributesByKey']);

        // bool Memcached::set ( string $key , mixed $value [, int $expiration ] )
        opencensus_trace_method('Memcached', 'set', [self::class, 'handleAttributes']);

        // bool Memcached::setByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
        opencensus_trace_method('Memcached', 'setByKey', [self::class, 'handleAttributesByKey']);

        // bool Memcached::setMulti ( array $items [, int $expiration ] )
        opencensus_trace_method('Memcached', 'setMulti', [self::class, 'handleSetMulti']);

        // bool Memcached::setMultiByKey ( string $server_key , array $items [, int $expiration ] )
        opencensus_trace_method('Memcached', 'setMultiByKey', [self::class, 'handleSetMultiByKey']);
    }
595242
def write(self, data, debug_info=None):
        
        self.num_write_bytes += len(data)
        if self.debug:
            if not debug_info:
                debug_info = str(len(data))
            sys.stderr.write("%s: WRITE %s:\n%s\n" % (
                self.__class__.__name__,
                debug_info,
                pyhsm.util.hexdump(data)
            ))
        write_sock(self.socket_file, CMD_WRITE, data)
        return read_sock(self.socket_file)
566285
def log(self, name, val, **tags):
        """"""
        global _last_timestamp, _last_metrics

        # do not allow .log after closing
        assert not self.done.is_set(), "worker thread has been closed"
        # check if valid metric name
        assert all(c in _valid_metric_chars for c in name), "invalid metric name " + name

        val = float(val)  #Duck type to float/int, if possible.
        if int(val) == val:
            val = int(val)

        if self.host_tag and 'host' not in tags:
            tags['host'] = self.host_tag

        # get timestamp from system time, unless it's supplied as a tag
        timestamp = int(tags.pop('timestamp', time.time()))

        assert not self.done.is_set(), "tsdb object has been closed"
        assert tags != {}, "Need at least one tag"

        tagvals = ' '.join(['%s=%s' % (k, v) for k, v in tags.items()])

        # OpenTSDB has major problems if you insert a data point with the same
        # metric, timestamp and tags. So we keep a temporary set of what points
        # we have sent for the last timestamp value. If we encounter a duplicate,
        # it is dropped.
        unique_str = "%s, %s, %s, %s, %s" % (name, timestamp, tagvals, self.host, self.port)
        if timestamp == _last_timestamp or _last_timestamp == None:
            if unique_str in _last_metrics:
                return  # discard duplicate metrics
            else:
                _last_metrics.add(unique_str)
        else:
            _last_timestamp = timestamp
            _last_metrics.clear()

        line = "put %s %d %s %s\n" % (name, timestamp, val, tagvals)

        try:
            self.q.put(line, False)
            self.queued += 1
        except queue.Full:
            print("potsdb - Warning: dropping oldest metric because Queue is full. Size: %s" % self.q.qsize(), file=sys.stderr)
            self.q.get()  #Drop the oldest metric to make room
            self.q.put(line, False)
        return line
795717
def write_changelog(debug=False):
    """"""
    changelog = _iter_log_oneline(debug)
    if changelog:
        changelog = _iter_changelog(changelog)
    if not changelog:
        return
    if debug:
        print('Writing ChangeLog')
    new_changelog = os.path.join(os.path.curdir, 'ChangeLog')
    # If there's already a ChangeLog and it's not writable, just use it
    if (os.path.exists(new_changelog)
            and not os.access(new_changelog, os.W_OK)):
        return
    with io.open(new_changelog, 'w', encoding='utf-8') as changelog_file:
        for release, content in changelog:
            changelog_file.write(content)
929592
def dump_to_log(self, logger):
        """"""
        logger.error("Execution ended in %s for cmd %s", self._retcode, self._cmd)
        for line in self._collected_stdout:
            logger.error(STDOUT_LOG_PREFIX + line)
846024
protected void writeLogging(Definition def, Writer out, int indent, String level, String content, String... params)
         throws IOException
   {
      writeIndent(out, indent);
      if (def.isSupportJbossLogging())
      {
         out.write("log.trace");
         int size = params.length;
         if (size > 0)
            out.write("f");
         out.write("(\"" + content + "(");
         for (int i = 0; i < size; i++)
         {
            out.write("%s");
            if (i < size - 1)
               out.write(", ");
         }
         out.write(")\"");
         for (int i = 0; i < size; i++)
         {
            out.write(", ");
            out.write(params[i]);
         }
         out.write(");");
      }
      else
      {
         out.write("log.finest(\"" + content + "()\");");
      }
      writeEol(out);
   }
1169278
def log_writer():
    ''''''
    while True:
        mpstate.logfile_raw.write(bytearray(mpstate.logqueue_raw.get()))
        timeout = time.time() + 10
        while not mpstate.logqueue_raw.empty() and time.time() < timeout:
            mpstate.logfile_raw.write(mpstate.logqueue_raw.get())
        while not mpstate.logqueue.empty() and time.time() < timeout:
            mpstate.logfile.write(mpstate.logqueue.get())
        if mpstate.settings.flushlogs or time.time() >= timeout:
            mpstate.logfile.flush()
            mpstate.logfile_raw.flush()
1256645
def write_cache(self):
        """"""
        doc = {
            '__format__': 1,
            'dependencies': self._cache,
        }
        with open(self._cache_file, 'w') as f:
            json.dump(doc, f, sort_keys=True)