Handles logging.

        | Logs to a sql db.
420607
def do_log(self, target, nick, msg, msgtype):
        
        if not isinstance(msg, str):
            raise Exception("IRC doesn't like it when you send it a %s" % type(msg).__name__)
        target = target.lower()
        flags = 0
        # Properly handle /msg +#channel
        if target.startswith(('+', '@')):
            target = target[1:]
        with self.data_lock:
            if target in self.channels:
                if self.opers[target].get(nick, False):
                    flags |= 1
                if self.voiced[target].get(nick, False):
                    flags |= 2
            else:
                target = 'private'
        # FIXME: should we special-case this?
        # strip ctrl chars from !creffett
        msg = msg.replace('\x02\x038,4', '<rage>')
        self.db.log(nick, target, flags, msg, msgtype)

        if self.log_to_ctrlchan:
            ctrlchan = self.config['core']['ctrlchan']
            if target != ctrlchan:
                ctrlmsg = "%s:%s:%s:%s" % (target, msgtype, nick, msg)
                # If we call self.send, we'll get a infinite loop.
                self.connection.privmsg(ctrlchan, ctrlmsg.strip())
33112
public function execute()
	{
		$this->connect();

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// Execute the query.
		$this->executed = false;

		if ($this->prepared instanceof \mysqli_stmt)
		{
			// Bind the variables:
			if ($this->sql instanceof PreparableInterface)
			{
				$bounded =& $this->sql->getBounded();

				if (\count($bounded))
				{
					$params     = array();
					$typeString = '';

					foreach ($bounded as $key => $obj)
					{
						// Add the type to the type string
						$typeString .= $obj->dataType;

						// And add the value as an additional param
						$params[] = $obj->value;
					}

					// Make everything references for call_user_func_array()
					$bindParams   = array();
					$bindParams[] = &$typeString;

					for ($i = 0, $iMax = \count($params); $i < $iMax; $i++)
					{
						$bindParams[] = &$params[$i];
					}

					\call_user_func_array(array($this->prepared, 'bind_param'), $bindParams);
				}
			}

			$this->executed = $this->prepared->execute();
			$this->cursor   = $this->prepared->get_result();

			// If the query was successful and we did not get a cursor, then set this to true (mimics mysql_query() return)
			if ($this->executed && !$this->cursor)
			{
				$this->cursor = true;
			}
		}

		// If an error occurred handle it.
		if (!$this->executed)
		{
			$this->errorNum = (int) $this->connection->errno;
			$this->errorMsg = (string) $this->connection->error;

			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (ConnectionFailureException $e)
				{
					// If connect fails, ignore that exception and throw the normal exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}; Failed query: {sql}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)
					);

					throw new ExecutionFailureException($sql, $this->errorMsg, $this->errorNum);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}

			// The server was not disconnected.
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}; Failed query: {sql}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)
			);

			throw new ExecutionFailureException($sql, $this->errorMsg, $this->errorNum);
		}

		return $this->cursor;
	}
508936
@Override
    protected void doLogSql() {
        //here we only print prepared sql statement.
        LOG.info("Prepared SQL：" + getSqlDriver().preparedBatchInsertionSql(this).fst);
    }
1304982
def setup_logging():
    
    fmt = 'DBG<0>%(pathname)s:%(lineno)d  %(funcName)s: %(message)s'

    handler_stderr = logging.StreamHandler(sys.stderr)
    handler_stderr.setFormatter(logging.Formatter(fmt))

    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)
    root_logger.addHandler(handler_stderr)
588854
public function execute() {
        if (\core\task\database_logger::class == \core\task\logmanager::get_logger_classname()) {
            \core\task\database_logger::cleanup();
        }
    }
128296
def db_exec_literal(self, sql: str) -> int:
        """"""
        self.ensure_db_open()
        cursor = self.db.cursor()
        debug_sql(sql)
        try:
            cursor.execute(sql)
            return cursor.rowcount
        except:  # nopep8
            log.exception("db_exec_literal: SQL was: " + sql)
            raise
692270
def execute(self, sql):
        """"""
        cursor = self.connection.cursor()
        try:
            cursor.execute(sql)
        finally:
            cursor.close()
790878
def handle(self):
        
        database = self.option("database")

        self.resolver.set_default_connection(database)

        repository = DatabaseMigrationRepository(self.resolver, "migrations")

        migrator = Migrator(repository, self.resolver)

        if not migrator.repository_exists():
            return self.error("No migrations found")

        self._prepare_database(migrator, database)

        path = self.option("path")

        if path is None:
            path = self._get_migration_path()

        ran = migrator.get_repository().get_ran()

        migrations = []
        for migration in migrator._get_migration_files(path):
            if migration in ran:
                migrations.append(["<fg=cyan>%s</>" % migration, "<info>Yes</>"])
            else:
                migrations.append(["<fg=cyan>%s</>" % migration, "<fg=red>No</>"])

        if migrations:
            table = self.table(["Migration", "Ran?"], migrations)
            table.render()
        else:
            return self.error("No migrations found")

        for note in migrator.get_notes():
            self.line(note)
872280
protected void handleSqlCount(ActionRuntime runtime) {
        final CallbackContext context = CallbackContext.getCallbackContextOnThread();
        if (context == null) {
            return;
        }
        final SqlStringFilter filter = context.getSqlStringFilter();
        if (filter == null || !(filter instanceof ExecutedSqlCounter)) {
            return;
        }
        final ExecutedSqlCounter counter = ((ExecutedSqlCounter) filter);
        final int sqlExecutionCountLimit = getSqlExecutionCountLimit(runtime);
        if (sqlExecutionCountLimit >= 0 && counter.getTotalCountOfSql() > sqlExecutionCountLimit) {
            // minus means no check here, by-annotation cannot specify it, can only as default limit
            // if it needs to specify it by-annotation, enough to set large size
            handleTooManySqlExecution(runtime, counter, sqlExecutionCountLimit);
        }
        saveRequestedSqlCount(counter);
    }
302328
def _init_logging(verbose):
    """"""
    hdlr = logging.StreamHandler()
    hdlr.setFormatter(logging.Formatter(
        '%(asctime)s [%(levelname)s] [%(module)s] %(message)s'))
    LOG.addHandler(hdlr)
    if verbose:
        LOG.setLevel(logging.DEBUG)
        LOG.debug('Verbose output enabled.')
    else:
        LOG.setLevel(logging.INFO)
7222
def log(self, msg, *args):
        """"""
        if args:
            msg %= args
        click.echo(msg, file=sys.stderr)
670573
def post(self):
        '''
        '''
        ## format sql

        data = request.get_json()
        options, sql_raw = data.get('options'), data.get('sql_raw')

        if options == 'format':
            sql_formmated = sqlparse.format(sql_raw, keyword_case='upper', reindent=True)
            return build_response(dict(data=sql_formmated, code=200))

        elif options in ('all', 'selected'):
            conn = SQL(config.sql_host, config.sql_port, config.sql_user,
                       config.sql_pwd, config.sql_db)

            result = conn.run(sql_raw)
            return build_response(dict(data=result, code=200))
        else:

            pass







        pass
807677
void log(LogRecord record, boolean wasForced) {
    // Do the fast boolean check (which normally succeeds) before calling isLoggable().
    if (!wasForced || logger.isLoggable(record.getLevel())) {
      // Unforced log statements or forced log statements at or above the logger's level can be
      // passed to the normal log(LogRecord) method.
      logger.log(record);
    } else {
      // If logging has been forced for a log record which would otherwise be discarded, we cannot
      // call our logger's log(LogRecord) method, so we must simulate its behavior in one of two
      // ways.
      // 1: Simulate the effect of calling the log(LogRecord) method directly (this is safe if the
      //    logger provided by the log manager was a normal Logger instance).
      // 2: Obtain a "child" logger from the log manager which is set to log everything, and call
      //    its log(LogRecord) method instead (which should have the same overridden behavior and
      //    will still publish log records to our logger's handlers).
      //
      // In all cases we still call the filter (if one exists) even though we ignore the result.
      // Use a local variable to avoid race conditions where the filter can be unset at any time.
      Filter filter = logger.getFilter();
      if (filter != null) {
        filter.isLoggable(record);
      }
      if (logger.getClass() == Logger.class || cannotUseForcingLogger) {
        // If the Logger instance is not a subclass, its log(LogRecord) method cannot have been
        // overridden. That means it's safe to just publish the log record directly to handlers
        // to avoid the loggability check, which would otherwise discard the forced log record.
        publish(logger, record);
      } else {
        // Hopefully rare situation in which the logger is subclassed _and_ the log record would
        // normally be discarded based on its level.
        forceLoggingViaChildLogger(record);
      }
    }
  }
808909
private void doWrite(final LogEntry logEntry) throws SQLException {
		if (checkConnection()) {
			if (batch) {
				batchCount += 1;
			}

			try {
				for (int i = 0; i < tokens.size(); ++i) {
					tokens.get(i).apply(logEntry, statement, i + 1);
				}
			} catch (SQLException ex) {
				resetConnection();
				throw ex;
			}

			try {
				if (batch) {
					statement.addBatch();
					if (batchCount >= MAX_BATCH_SIZE) {
						statement.executeBatch();
						batchCount = 0;
					}
				} else {
					statement.executeUpdate();
				}
			} catch (SQLException ex) {
				resetConnection();
				throw ex;
			}
		} else {
			lostCount += 1;
		}
	}
1183596
def log(**data):
	
	# Get data from request body
	entry = {
		"module": data["params"]["module"],
		"event": data["params"]["event"],
		"timestamp": data["params"]["timestamp"],
		"arguments": data["params"]["arguments"]
	}
	# Call create metod for writing data to database
	history.create(entry)
563623
def setup_logging(self):
        
        logging.getLogger('amqp').setLevel(str_to_logging(self.get('logging', 'amqp')))
        logging.getLogger('rdflib').setLevel(str_to_logging(self.get('logging', 'rdflib')))
26663
def start_logging(out=_stdout, level='info'):
    
    global _log_level, _loggers, _started_logging
    if level not in log_levels:
        raise RuntimeError(
            "Invalid log level '{0}'; valid are: {1}".format(
                level, ', '.join(log_levels)
            )
        )

    if _started_logging:
        return

    _started_logging = True
    _log_level = level

    handler = _TxaioFileHandler(out)
    logging.getLogger().addHandler(handler)
    # note: Don't need to call basicConfig() or similar, because we've
    # now added at least one handler to the root logger
    logging.raiseExceptions = True  # FIXME
    level_to_stdlib = {
        'critical': logging.CRITICAL,
        'error': logging.ERROR,
        'warn': logging.WARNING,
        'info': logging.INFO,
        'debug': logging.DEBUG,
        'trace': logging.DEBUG,
    }
    logging.getLogger().setLevel(level_to_stdlib[level])
    # make sure any loggers we created before now have their log-level
    # set (any created after now will get it from _log_level
    for logger in _loggers:
        logger._set_log_level(level)