Save log into file, and try to send via email to Developers
974092
public static function flushLog()
    {
        $last_flush_time = Settings::get('cms_tools_application_log_flush');
        if (NOW - $last_flush_time < 453600) {
            return; // We do not need stats too often, wait 7 days
        }

        // Send data to original developer site of the existing domain
        self::sendInformation();

        // Now prepare file with aggregated data
        $app_log = new AppLogEntityRepository();
        $app_log->addSimpleSelectFields(['id', 'ts', 'user_id', 'url', 'msg', 'p', 'do']);
        if ($last_flush_time) {
            $app_log->setWhereOld($last_flush_time);
        }
        $app_log->addOrderByField('ts', true);
        $app_log->setGenerateOutputWithIterator(false);

        $users = new AdminUserRepository();
        $users->setGenerateOutputWithIterator(false);
        $users->addSimpleSelectFieldsAsString('CONCAT(`' . $users->getDbTableName() . '`.`name`, " ", `' . $users->getDbTableName() . '`.`surname`) AS `user`');

        $app_log->mergeWithCollection($users, 'user_id');

        $data_log = $app_log->getAsArrayOfObjectData(true);

        $usage = new AdminUsageEntityRepository();

        $data_usage = $usage->getAsArrayOfObjectData(true);

        if ($data_log || $data_usage) {
            $data = [
                'data' => [
                    'domain' => CFG_DOMAIN,
                    'cms_address' => DIR_CMS_URL,
                    'ts' => NOW,
                ],
                'logs' => [
                    'app_log' => $data_log,
                    'usage' => $data_usage,
                ]
            ];

            // Save in file
            if (!file_exists(DIR_CACHE)) {
                FileSystem::mkDir(DIR_CACHE);
            }

            file_put_contents(DIR_CACHE . 'log_data', gzencode(json_encode($data)));

            // Send stats
            @Mailer::getInstance()
                ->setSubject('Application and Usage log from ' . Configuration::getInstance()->get('site')['name'] . ' (till ' . date(Constants::FORMAT_CMS_DATETIME_FORMAT, NOW) . ')')
                ->setSender(Configuration::getInstance()->get('site')['email'])
                ->setRecipient(CMS_SUPPORT_EMAIL)
                ->setMessage('View attached file')
                ->addAttachment(DIR_CACHE . 'log_data')
                ->send();

            q('DELETE FROM `' . $usage->getDbTableName() . '`');
        }

        Settings::getInstance()->set('cms_tools_application_log_flush', NOW);
    }
1102002
def logging_feature(app):
    

    # this is important because otherwise only log warn, err and crit
    app.logger.setLevel(logging.INFO)

    # enable loggers
    email_exceptions = app.config.get('LOGGING_EMAIL_EXCEPTIONS_TO_ADMINS')
    if email_exceptions and not app.debug and not app.testing:
        # config.debug=False
        mail_handler = mail_logger(app)
        app.logger.addHandler(mail_handler)

    if not app.testing:
        file_handler = file_logger(app)
        app.logger.addHandler(file_handler)
884199
function doLogin(req, user, callback) {
	req.logIn(user, function(err) {
		if (err) {
			logger.error(err);
			return callback(err);
		}
		user.login_timestamp = Date.now();
		fileUtil.getMetastoreSafe(req).then(function(store) {
			store.updateUser(user.username, user, function(err) {
				if (err) {
					logger.error(err);
					return callback(err);
				}
				callback(null);
			});
		}, function noMetastore(err) {
			callback(err);
		});
	});
}
1240170
def email(to='medusa@sweeting.me', _from=default_from, subject='BOT MSG', message="Info email", attachments=None):
    """"""
    for attachment in attachments or []:
        filename = attachment.strip()
        try:
            result = run_cmd('uuencode %s %s | mailx -s "%s" %s' % (filename, filename, subject, to))[0]
            return "Sending email From: %s; To: %s; Subject: %s; Attachment: %s (%s)" % (_from, to, subject, filename, result or 'Succeded')
        except Exception as error:
            return str(error)

    if not attachments:
        p = os.popen("/usr/sbin/sendmail -t", "w")
        p.write("From: %s\n" % _from)
        p.write("To: %s\n" % to)
        p.write("Subject: %s\n" % subject)
        p.write("\n")   # blank line separating headers from body
        p.write('%s\n' % message)
        result = p.close()

    if not result:
        return "Sent email From: %s; To: %s; Subject: %s; Attachments: %s)" % (_from, to, subject, ','.join(attachments or []))
    else:
        return "Error: %s. Please fix Postfix:\n %s" % (result, help_str)
214233
function sendMail(opt, callback){
	var fileName = path.normalize(path.join(__dirname, opt.template));
	fs.readFile(fileName, 'utf8', function (err,data) {
		if (err) {
			return callback(err);
		}
		const authUrl = opt.req.protocol + '://' + opt.req.get('host') + opt.auth + opt.user.authToken;
		let emailText  = data.replace(/<EMAIL>/g, opt.user.email || "");
		emailText  = emailText.replace(/<USER>/g, opt.user.username || "");
		emailText  = emailText.replace(/<URL>/g, authUrl);
		emailText  = emailText.replace(/<PASSWORD>/g, opt.pwd || "");
		const subjLineIndex = emailText.indexOf("\n"),
			subject = emailText.substr(0, subjLineIndex),
			body = emailText.substr(subjLineIndex),
			smtpConfig = {
				host: opt.options.configParams.get("mail.smtp.host"),
				port: opt.options.configParams.get("mail.smtp.port"),
				secure: true,
				auth: {
					user: opt.options.configParams.get("mail.smtp.user"),
					pass: opt.options.configParams.get("mail.smtp.password")
				}
			};
		if (opt.options.configParams.get("mail.from")) {
			const transport = nodemailer.createTransport(smtpConfig);
			const mailOptions = {
				from: opt.options.configParams.get("mail.from"),
				to: opt.user.email,
				subject: subject,
				text: body, 
			};
			transport.sendMail(mailOptions, function(error, info) {
				if (error) {
					logger.error(error + " " + info);
					callback(error);
				}
				callback(null, info);
			});
		} else {
			// used for local dev testing (no email is sent, logged to console)
			logger.info(body);
			callback(null);
		}
	});
}
303061
def log_to_file(logdir, mode='a', delete=False, clearmem=True):
    
    logger = FileLogger(logdir, mode, delete, clearmem)
    _loggers.append(logger)
    return log_to(logger)
813674
def user_save_event(user):
    
    msg = 'User ({}){} updated/saved'.format(user.id, user.email)
    current_app.logger.info(msg)
163050
def submit(command_filename, workingdir, send_mail = False, username = None):
    ''''''
    return sge_interface.submit(command_filename, workingdir, send_mail = send_mail, username = username)
923902
public function update_logging()
    {
        $config = $this->app->make('config');
        if (!$this->token->validate('update_logging')) {
            $this->error->add($this->token->getErrorMessage());
        }
        if ($this->request->request->get('handler') == 'file' && $this->request->request->get('logging_mode')) {
            $logFile = $this->request->request->get('logFile');
            $filesystem = new Filesystem();
            $directory = dirname($logFile);
            if ($filesystem->isFile($logFile) && !$filesystem->isWritable($logFile)) {
                $this->error->add(t('Log file exists but is not writable by the web server.'));
            }
            if (!$filesystem->isFile($logFile) && (!$filesystem->isDirectory($directory) || !$filesystem->isWritable($directory))) {
                $this->error->add(t('Log file does not exist on the server. The directory of the file provided must exist and be writable on the web server.'));
            }
            $filename = basename($logFile);
            if (!$filename || substr($filename, -4) != '.log') {
                $this->error->add(t('The filename provided must be a valid filename and end with .log'));
            }
        }
        if (!$this->error->has()) {
            $intLogErrorsPost = $this->post('ENABLE_LOG_ERRORS') == 1 ? 1 : 0;
            $intLogEmailsPost = $this->post('ENABLE_LOG_EMAILS') == 1 ? 1 : 0;

            $config->save('concrete.log.errors', $intLogErrorsPost);
            $config->save('concrete.log.emails', $intLogEmailsPost);

            $mode = $this->request->request->get('logging_mode');
            if ($mode != 'advanced') {
                $mode = 'simple';
                $config->save('concrete.log.configuration.simple.core_logging_level',
                    $this->request->request->get('logging_level')
                );
                $config->save('concrete.log.configuration.simple.handler',
                    $this->request->request->get('handler')
                );
                $config->save('concrete.log.configuration.simple.file.file',
                    $this->request->request->get('logFile')
                );
            }
            $config->save('concrete.log.enable_dashboard_report',
                $this->request->request->get('enable_dashboard_report') ? true : false);
            $config->save('concrete.log.configuration.mode', $mode);

            $this->redirect('/dashboard/system/environment/logging', 'logging_saved');
        }
        $this->view();
    }
676605
def send_file(message, file)
      response = self.class.post(@api.send_file_config[:url],
        :query => { :auth_token => @token },
        :body => file_body({ :message => message }.send(@api.send_config[:body_format]), file),
        :headers => file_body_headers(@api.headers)
      )

      ErrorHandler.response_code_to_exception_for :user, user_id, response
      true
    end
1350226
def main():
    
    import argparse

    parser = argparse.ArgumentParser(description='Send a (g)mail with yagmail.')
    subparsers = parser.add_subparsers(dest="command")
    oauth = subparsers.add_parser('oauth')
    oauth.add_argument(
        '--user', '-u', required=True, help='The gmail username to register oauth2 for'
    )
    oauth.add_argument(
        '--file', '-f', required=True, help='The filepath to store the oauth2 credentials'
    )
    parser.add_argument('-to', '-t', help='Send an email to address "TO"', nargs='+')
    parser.add_argument('-subject', '-s', help='Subject of email', nargs='+')
    parser.add_argument('-contents', '-c', help='Contents to send', nargs='+')
    parser.add_argument('-attachments', '-a', help='Attachments to attach', nargs='+')
    parser.add_argument('-user', '-u', help='Username')
    parser.add_argument('-oauth2', '-o', help='OAuth2 file path')
    parser.add_argument(
        '-password', '-p', help='Preferable to use keyring rather than password here'
    )
    args = parser.parse_args()
    args.contents = (
        args.contents if args.contents else (sys.stdin.read() if not sys.stdin.isatty() else None)
    )
    if args.command == "oauth":
        user = args.user
        SMTP(args.user, oauth2_file=args.file)
        print("Succesful.")
    else:
        yag = SMTP(args.user, args.password, oauth2_file=args.oauth2)
        yag.send(
            to=args.to, subject=args.subject, contents=args.contents, attachments=args.attachments
        )
65383
def send_mail_worker(config, mail, event):
    """"""
    log = ""

    try:
        if config.mail_ssl:
            server = SMTP_SSL(config.mail_server, port=config.mail_server_port, timeout=30)
        else:
            server = SMTP(config.mail_server, port=config.mail_server_port, timeout=30)

        if config.mail_tls:
            log += 'Starting TLS\n'
            server.starttls()

        if config.mail_username != '':
            log += 'Logging in with ' + str(config.mail_username) + "\n"
            server.login(config.mail_username, config.mail_password)
        else:
            log += 'No username, trying anonymous access\n'

        log += 'Sending Mail\n'
        response_send = server.send_message(mail)
        server.quit()

    except timeout as e:
        log += 'Could not send email to enrollee, mailserver timeout: ' + str(e) + "\n"
        return False, log, event

    log += 'Server response:' + str(response_send)
    return True, log, event
616498
public void dumpDebugFile() {
    try {
      File f = File.createTempFile("elki-debug", ".svg");
      f.deleteOnExit();
      this.saveAsSVG(f);
      LoggingUtil.warning("Saved debug file to: " + f.getAbsolutePath());
    }
    catch(Throwable err) {
      // Ignore.
    }
  }
186297
public function save($log_dir = '')
    {
        if (empty($log_dir)) {
            $log_dir = \ROOT . '/private/logs/syslog/';
        }

        if (!is_dir($log_dir)) {
            mkdir($log_dir, 0777, true);
        }

        return file_put_contents($log_dir . date('Y_m_d') . '.log',
                $this->message . "\n", \FILE_APPEND);
    }
273977
def send_text_file(self, text_file, sender=None, recipient=None):
        
        log = logging.getLogger(self.cls_logger + '.send_text_file')

        if not isinstance(text_file, basestring):
            msg = 'arg text_file must be a string, found type: {t}'.format(t=text_file.__class__.__name__)
            raise AssetMailerError(msg)

        if not os.path.isfile(text_file):
            msg = 'The provided text_file was not found or is not a file: {f}'.format(f=text_file)
            raise AssetMailerError(msg)

        # Determine sender/recipient
        if sender is None:
            sender = default_sender_email
        if recipient is None:
            recipient = self.recipient_email

        # Set the email subject
        file_name = text_file.split(os.path.sep)[-1]
        subject = self.subject + file_name

        # Read the input text file
        try:
            fp = open(text_file, 'rb')
            mail_message = MIMEText(fp.read())
            fp.close()
        except OSError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem reading text file: {f}\n{e}'.format(
                n=ex.__class__.__name__, f=text_file, e=str(ex))
            raise AssetMailerError, msg, trace

        # Configure the mail message
        mail_message['Subject'] = subject
        mail_message['From'] = sender
        mail_message['To'] = recipient

        # Configure the SMTP server
        log.debug('Configuring the SMTP server...')
        try:
            s = smtplib.SMTP(self.smtp_server)
        except (smtplib.SMTPConnectError, socket.timeout, socket.error):
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem connecting to SMTP server: {s}\n{e}'.format(
                n=ex.__class__.__name__, s=self.smtp_server, e=str(ex))
            raise AssetMailerError, msg, trace

        # Set the SMTP log level
        # s.set_debuglevel(debuglevel=__debug__)

        # Set the SMTP server to be localhost
        log.debug('Sending email with subject {s} to {e}...'.format(s=subject, e=recipient))
        try:
            s.sendmail(sender, [recipient], mail_message.as_string())
        except smtplib.SMTPRecipientsRefused:
            _, ex, trace = sys.exc_info()
            msg = '{n}: All recipients were refused, nobody got the mail: {r}:\n{e}'.format(
                n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPSenderRefused:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server did not accept the sender address: {s}:\n{e}'.format(
                n=ex.__class__.__name__, s=sender, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPHeloError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server did not respond to the HELO greeting\n{e}'.format(
                n=ex.__class__.__name__, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPDataError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server replied with an unexpected error code (other than a refusal of a recipient)\n{e}'.\
                format(n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPConnectError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a connection error\n{e}'. \
                format(n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        else:
            log.info('Sent email to: {r}'.format(r=recipient))
        finally:
            s.quit()
1058723
def SendEmail(self, client_id, message):
    """"""
    logging.info(self.logline, client_id, message)

    client_info = None
    hostname = None

    # Write crash data.
    if data_store.RelationalDBEnabled():
      client = data_store.REL_DB.ReadClientSnapshot(client_id)
      if client is not None:
        client_info = client.startup_info.client_info
        hostname = client.knowledge_base.fqdn
    else:
      client = aff4.FACTORY.Open(client_id, token=self.token)
      client_info = client.Get(client.Schema.CLIENT_INFO)
      hostname = client.Get(client.Schema.FQDN)

    crash_details = rdf_client.ClientCrash(
        client_id=client_id,
        client_info=client_info,
        crash_message=message,
        timestamp=int(time.time() * 1e6),
        crash_type="Nanny Message")

    WriteAllCrashDetails(client_id, crash_details, token=self.token)

    # Also send email.
    if config.CONFIG["Monitoring.alert_email"]:
      url = "/clients/%s" % client_id
      body = self.__class__.mail_template.render(
          client_id=client_id,
          admin_ui=config.CONFIG["AdminUI.url"],
          hostname=utils.SmartUnicode(hostname),
          signature=config.CONFIG["Email.signature"],
          url=url,
          message=utils.SmartUnicode(message))
      email_alerts.EMAIL_ALERTER.SendEmail(
          config.CONFIG["Monitoring.alert_email"],
          "GRR server",
          self.subject % client_id,
          utils.SmartStr(body),
          is_html=True)
1194114
private void openLog()
  {
    closeLogStream();

    WriteStream os = _os;
    _os = null;

    IoUtil.close(os);

    Path path = getPath();

    if (path == null) {
      path = getPath(CurrentTime.currentTime());
    }

    Path parent = path.getParent();

    try {
      if (! Files.isDirectory(parent)) {
        Files.createDirectory(parent);
      }
    } catch (Exception e) {
      logWarning(L.l("Can't create log directory {0}.\n  Exception={1}",
                     parent, e), e);
    }

    Exception exn = null;

    for (int i = 0; i < 3 && _os == null; i++) {
      try {
        OutputStream out = Files.newOutputStream(path, StandardOpenOption.APPEND);
        _os = new WriteStream(out);
      } catch (IOException e) {
        exn = e;
      }
    }

    String pathName = path.toString();

    try {
      if (pathName.endsWith(".gz")) {
        _zipOut = _os;
        _os = new WriteStream(new GZIPOutputStream(_zipOut));
      }
      else if (pathName.endsWith(".zip")) {
        throw new ConfigException("Can't support .zip in path-format");
      }
    } catch (Exception e) {
      if (exn == null)
        exn = e;
    }

    if (exn != null)
      logWarning(L.l("Can't create log for {0}.\n  User={1} Exception={2}",
                     path, System.getProperty("user.name"), exn), exn);
  }