承接 cornernote/yii2-audit 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

cornernote/yii2-audit

Composer 安装命令:

composer require cornernote/yii2-audit

包简介

Auditing component for Yii2

README 文档

README

Join Chat Latest Version Software License Build Status Coverage Status Quality Score Total Downloads

Yet another auditing module. This is based on a couple of other projects out there:

Features

Installs as a simple module so it can be added without too much hassle.

  • Tracks all incoming pageviews with the ability to add custom data to a view. It logs the user-id (if any), IP, superglobals ($_GET/$_POST/$_SERVER/$_FILES/$_COOKIES), memory usage, referrer and origin. You can either track specific actions and nothing else or exclude specific routes from logging (wildcard supported).

  • Track database changes. By implementing the AuditingBehavior this is easily realized thanks to a modified version of Sammayes Yii2 Audit Trail.

  • Automatically log javascript errors. Errors and warning are logged automatically (if you activate the functionality), but the javascript component also provides methods to manually add logging entries.

  • View your data. The module contains a nice viewer that is automatically made available when you add it to your configuration. It has configurable permissions to limit access to this functionality, both by roles or by user-id.

Installing

  • Run composer.phar require --prefer-dist bedezign/yii2-audit "*" or add a require line to your composer.json: 'bedezign/yii2-audit: "*".
  • Run the migrations from the migrations folder to create the relevant tables: yii migrate --migrationPath=@bedezign/yii2/audit/migrations
  • Add a module to your configuration (with optional extra settings) and if it needs to auto trigger, also add it to the bootstrap:

Example:

'bootstrap' => ['log', 'auditing', ...],
'controllerNamespace' => 'frontend\controllers',

'modules' => [
    'auditing' => [
        'class' => 'bedezign\yii2\audit\Auditing',
        'ignoreActions' => 'debug/*',
    ],
],

This installs the module with auto loading, instructing it to not log anything debug related.

Additional options

'modules' => [
    'auditing' => [
        'class' => 'bedezign\yii2\audit\Auditing',
        'db' => 'db', // Name of the component to use for database access
        'trackActions' => ['*'], // List of actions to track. '*' is allowed as the last character to use as wildcard
        'ignoreActions' => 'debug/*', // Actions to ignore. '*' is allowed as the last character to use as wildcard (eg 'debug/*')
        'truncateChance' => 75, // Chance in % that the truncate operation will run, false to not run at all
        'maxAge' => 'debug', // Maximum age (in days) of the audit entries before they are truncated
        'accessUsers' => [1, 2], // (List of) user(s) IDs with access to the viewer, null for everyone (if the role matches)
        'accessRoles' => ['admin'], // (List of) role(s) with access to the viewer, null for everyone (if the user matches)
    ],
],

Word of caution: The module is configured by default to only allow viewing access to users with the role 'admin'. This functionality is only available in Yii if you have enabled RBAC (via the authManager-component). If not, please set this option to null. If you do so you should consider activating the accessUsers-option, you don't want to give everyone access to your auditing data!

Error Logging

If you want errors to be logged, you have to register the included errorhandler as well in you configuration:

'errorHandler' => [
   'class' => '\bedezign\yii2\audit\components\web\ErrorHandler',
   'errorAction' => 'site/error',
],

Database changes

If you want database changes to be logged, you have to add the AuditingBehavior to the models you want to log.

public function behaviors()
{
    return [
        'bedezign\yii2\audit\AuditingBehavior'
    ];
}

Additional options

public function behaviors()
{
    return [
        'LoggableBehavior' => [
            'class' => 'sammaye\audittrail\LoggableBehavior',
            'allowed' => ['some_field'], // Array with fields to save. You don't need to configure both `allowed` and `ignored`
            'ignored' => ['another_field'], // Array with fields to ignore. You don't need to configure both `allowed` and `ignored`
            'ignoredClasses' => ['common\models\Model'], // Array with classes to ignore
            'skipNulls' => false, // Skip fields where bouth old and new values are NULL
            'active' => true // Is the behavior is active or not
        ]
    ];
}

Only log database changes

If you only want to log the database changes you should use the following module setting. All pageview logging will be ignored.

'modules' => [
    'auditing' => [
        'class' => 'bedezign\yii2\audit\Auditing',
        'ignoreActions' => ['*'],
    ],
],

There is a grid for only database changes available at:

http://localhost/path/to/index.php?r=auditing/default/trail

Render Audit Log for a Model

Model:

    /** get trails for this model */
    public function getAuditTrails()
    {
        return $this->hasMany(AuditTrail::className(), ['model_id' => 'id'])
            ->andOnCondition(['model' => get_class($this)]);
    }
    /** get trails for this model and all related comment models */
    public function getAuditTrails()
    {
        return AuditTrail::find()
            ->orOnCondition([
                'audit_trail.model_id' => $this->id, 
                'audit_trail.model' => get_class($this),
              ])
            ->orOnCondition([
                'audit_trail.model_id' => ArrayHelper::map($this->getComments()->all(), 'id', 'id'), 
                'audit_trail.model' => 'app\models\Comment',
            ]);
    }

Controller:

    public function actionLog($id)
    {
        $model = $this->findModel($id);
        return $this->render('log', ['model' => $model]);
    }

View

echo $this->render('@vendor/bedezign/yii2-audit/views/_audit_trails', [
    // model to display audit trais for, must have a getAuditTrails() method
    'model' => $model,
    // params for the AuditTrailSearch::search() (optional)
    'params' => [
        'AuditTrailSearch' => [
            'field' => 'status', // in this case we only want to show trails for the "status" field
        ]
    ],
]);

Javascript Logging

The module also supports logging of javascript errors, warnings and even regular log entries. To activate, register the assets\JSLoggingAsset in any of your views:

 \bedezign\yii2\audit\assets\JSLoggingAsset::register($this);

This will activate the logger automatically. By default all warnings and errors are transmitted to the backend.

The default configuration assumes that the module was added as "auditing" (so the log url would be "/auditing/javascript/log"). If that is not the case, please make sure to update the setting somewhere in your javascript:

window.jsLogger.logUrl = '/mymodulename/javascript/log';

All javascript logging will be linked to the entry associated with the page entry created when you performed the initial request. This is accomplished by adding the ID of that entry in the window-object (window.auditEntry).

Beware: If you use ajax or related technologies to load data from the backend, these requests might generate their own auditing entries. If those cause backend errors they will be linked to that new entry. This might be a bit weird with the javascript logging being linked to the older entry.

Extra Data

It is possible to add extra custom data to the current audit entry by simply calling:

\bedezign\yii2\audit\Auditing::current()->data('name', 'extra data can be an integer, string, array, object or whatever', 'optional type');

Or if you prefer:

\Yii::$app->auditing->data(('name', 'extra data can be an integer, string, array, object or whatever', 'optional type');

Emailing Errors

A command is available to email errors which can be added to your cron.

php yii auditing/error-email

You should ensure you have setup a mailer component and have a scriptUrl property in the urlManager component in your console configuration. For example:

$console = [
    'components' => [
        'mailer' => [
            // see http://www.yiiframework.com/doc-2.0/guide-tutorial-mailing.html
            'class' => 'yii\swiftmailer\Mailer',
        ],
        'urlManager' => [
            // required because the CLI script doesn't know the URL
            'scriptUrl' => 'http://example.com/',
        ],
    ],
]

Render AuditEntry.id in Layout

It is often useful for users to be able to report the AuditEntry.id to the developer. To render the ID to the page include the partial provided:

<?= $this->render('@vendor/bedezign/yii2-audit/views/_audit_entry_id', [
  'link' => false, // set to true to render the id as a link
]); ?>

Viewing the audit data

Assuming you named the module "auditing" you can then access the auditing module through the following URL:

http://localhost/path/to/index.php?r=auditing

If you would like to see all database changes individually you can access:

http://localhost/path/to/index.php?r=auditing/default/trail

Screenshots

Index example View example Diff example

cornernote/yii2-audit 适用场景与选型建议

cornernote/yii2-audit 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 47 次下载、GitHub Stars 达 1, 最近一次更新时间为 2015 年 06 月 19 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「module」 「Audit」 「trail」 「yii2」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 cornernote/yii2-audit 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 cornernote/yii2-audit 我们能提供哪些服务?
定制开发 / 二次开发

基于 cornernote/yii2-audit 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 47
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 22
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 117
  • 开发语言: PHP

其他信息

  • 授权协议: BSD
  • 更新时间: 2015-06-19