5m 中文文档教程

发布于 6年前 浏览 38 项目主页 更新于 3年前

5m

是一个接近实时的实用程序,5mb 或 5 分钟

KLP

安装 | 用例 | 注释来源 | License

Installation

npm i 5m

Use case

我将这个包与 debugaws-sdk 在 S3 上上传日志。

然后有一个触发器将在 S3 上创建的每个文件提供给 AWS Lambda 它将文件内容发送到使用 socket.io 广播它的服务器。 是的,我知道还有其他很棒的工具,如 CloudWatch、Kinesis 等。 (但是 5m 在演讲中是免费的,在啤酒中也是免费的;)

很酷的部分是每次都可以触发 AWS Lambda 创建一个新文件,例如将其加载到数据库中。

下面是一个示例代码,用于在 S3 上实现日志记录和上传。

// File: log.js
//
// Prints to STDOUT if DEBUG environment variable is set properly.
// Uploads logs on some S3 bucket.
//
//     const log = require('./log')
//     log('Hello world')
//

const AWS = require('aws-sdk')
const debug = require('debug')
const fiveM = require('5m')

const s3 = new AWS.S3()

// Use package name as namespace for logging, just as an example.
const pkg = require('./package.json')
const namespace = pkg.name
const debug5m = debug(`${namespace}:5m`)
const debugPkg = debug(namespace)

const writeOnS3 = (data) => {
  const Bucket = 'my-bucket'

  const tstamp = new Date().getTime()
  const Key = `my/path/${tstamp}.log`

  s3.upload({ Bucket, Key }, error => {
    if (error) debug5m(error)
    else debug5m()
  })
}

function log (message) {
  const tstamp = new Date().getTime()
  const record = `${tstamp} ${namespace} ${message}`

  fiveM(namespace, writeOnS3)(record)
  debugPkg(message)
}

module.exports = log

Annotated source

将数据存储在命名空间的桶中,以及其刷新数据的功能。

var bucket = {}
var flush = {}

考虑到 1 个字符应该是 1 个字节,并且日期以毫秒表示, 以下常量表示 5 MB5 分钟。 近似是可以的,因为我们想要实现近实时。 可以设置用于刷新数据的超时时间,用于测试或其他目的 通过 FIVEM_TIMEOUT_MILLISECONDS 环境变量。

const fiveMb = 1024 * 1024 * 5
const fiveMin = 300 * 1000
const flushTimeout = process.env.FIVEM_TIMEOUT_MILLISECONDS || fiveMin

确保退出时没有数据丢失。

process.on('exit', () => {
  for (var namespace in bucket) flush[namespace]()
})

创建 5m 函数。

因为 5m 可以作为 npm 包名,但不能作为 JavaScript 标识符,使用像 Vm 这样的罗马数字可能会造成混淆,所以也许 将函数命名为 fiveM 是个好主意。

/**
 * **@param** `{String}` namespace
 * **@param** `{Function}` write
 *
 * **@returns** `{Function}` logger
 */
function fiveM (namespace, write) {

创建命名空间 flush 函数:写入数据并清理。

  flush[namespace] = () => {
    if (bucket[namespace]) {
      write(bucket[namespace])

      delete bucket[namespace]
    }
  }

创建记录器 函数。

  /**
   * @param {*} data
   */
  return function logger (data) {

如有必要,初始化数据桶并设置超时以稍后刷新它。

    if (typeof bucket[namespace] === 'undefined') {
      bucket[namespace] = ''

      setTimeout(flush[namespace], flushTimeout)
    }

将数据附加到命名桶。

    bucket[namespace] += data

检查数据是否大于 5 MB

    const exceededSpace = bucket[namespace] && (bucket[namespace].length > 0) && (bucket[namespace].length > fiveMb)

如果是,请冲洗它!

    if (exceededSpace) flush[namespace]()
  }
}

导出 5m 函数。

module.exports = fiveM

License

麻省理工学院

5m

is a near real time utility, 5mb or 5min

KLP

Installation | Use case | Annotated source | License

Installation

npm i 5m

Use case

I use this package with debug and aws-sdk to upload logs on S3.

Then there is a trigger that feeds every file created on S3 to an AWS Lambda which sends file content to a server that broadcast it using socket.io. Yes I know there are other cool tools like CloudWatch, Kinesis, etc. (but 5m is free as in speach and free as in beer too ;)

The cool part is that it is possible to trigger an AWS Lambda every time a new file is created, and for example load it on a database.

Here is an example code to achieve logging and upload on S3.

// File: log.js
//
// Prints to STDOUT if DEBUG environment variable is set properly.
// Uploads logs on some S3 bucket.
//
//     const log = require('./log')
//     log('Hello world')
//

const AWS = require('aws-sdk')
const debug = require('debug')
const fiveM = require('5m')

const s3 = new AWS.S3()

// Use package name as namespace for logging, just as an example.
const pkg = require('./package.json')
const namespace = pkg.name
const debug5m = debug(`${namespace}:5m`)
const debugPkg = debug(namespace)

const writeOnS3 = (data) => {
  const Bucket = 'my-bucket'

  const tstamp = new Date().getTime()
  const Key = `my/path/${tstamp}.log`

  s3.upload({ Bucket, Key }, error => {
    if (error) debug5m(error)
    else debug5m()
  })
}

function log (message) {
  const tstamp = new Date().getTime()
  const record = `${tstamp} ${namespace} ${message}`

  fiveM(namespace, writeOnS3)(record)
  debugPkg(message)
}

module.exports = log

Annotated source

Store data in a namespaced bucket, as well as its function to flush data.

var bucket = {}
var flush = {}

Considering 1 char should be 1 byte, and dates are expressed in milliseconds, the following constants express 5 MB and 5 minutes. Aproximation is ok, since we want to achieve a near real time. The timeout used for flushing data can be set, for testing or other purpouse via the FIVEM_TIMEOUT_MILLISECONDS environment variable.

const fiveMb = 1024 * 1024 * 5
const fiveMin = 300 * 1000
const flushTimeout = process.env.FIVEM_TIMEOUT_MILLISECONDS || fiveMin

Make sure no data is lost on exit.

process.on('exit', () => {
  for (var namespace in bucket) flush[namespace]()
})

Create the 5m function.

Since 5m is allowed as npm package name, but not as JavaScript identifier, using a roman number like Vm can be confusing, so maybe naming the function as fiveM is a good idea.

/**
 * **@param** `{String}` namespace
 * **@param** `{Function}` write
 *
 * **@returns** `{Function}` logger
 */
function fiveM (namespace, write) {

Create the namespaced flush function: write data and clean up.

  flush[namespace] = () => {
    if (bucket[namespace]) {
      write(bucket[namespace])

      delete bucket[namespace]
    }
  }

Create the logger function.

  /**
   * @param {*} data
   */
  return function logger (data) {

If necessary, initialize data bucket and set timeout to flush it later.

    if (typeof bucket[namespace] === 'undefined') {
      bucket[namespace] = ''

      setTimeout(flush[namespace], flushTimeout)
    }

Append data to named bucket.

    bucket[namespace] += data

Check if data is bigger than 5 MB.

    const exceededSpace = bucket[namespace] && (bucket[namespace].length > 0) && (bucket[namespace].length > fiveMb)

If yes, flush it!

    if (exceededSpace) flush[namespace]()
  }
}

Export 5m function.

module.exports = fiveM

License

MIT

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文