tracy 正在参加 2021 年度 OSC 中国开源项目评选,请投票支持!
tracy 在 2021 年度 OSC 中国开源项目评选 中已获得 {{ projectVoteCount }} 票,请投票支持!
2021 年度 OSC 中国开源项目评选 正在火热进行中,快来投票支持你喜欢的开源项目!
2021 年度 OSC 中国开源项目评选 >>> 中场回顾
tracy 获得 2021 年度 OSC 中国开源项目评选「最佳人气项目」 !
授权协议 View license
开发语言 PHP
操作系统 跨平台
软件类型 开源软件
开源组织
地区 不详
投 递 者 首席测试
适用人群 未知
收录时间 2021-11-11

软件简介

Tracy - PHP debugger

Downloads this Month Tests Build Status Windows Latest Stable Version License

Introduction

Tracy library is a useful helper for everyday PHP programmers. It helps you to:

  • quickly detect and correct errors
  • log errors
  • dump variables
  • measure execution time of scripts/queries
  • see memory consumption

PHP is a perfect language for making hardly detectable errors because it gives great flexibility to programmers. Tracy\Debugger is more valuable because of that. It is an ultimate tool among the diagnostic ones. If you are meeting Tracy for the first time, believe me, your life starts to be divided into one before the Tracy and the one with her. Welcome to the good part!

Documentation can be found on the website.

Support Tracy

Do you like Tracy? Are you looking forward to the new features?

Buy me a coffee

Thank you!

Installation and requirements

The recommended way to is via Composer:

composer require tracy/tracy

Alternatively, you can download the whole package or tracy.phar file.

Tracy compatible with PHP compatible with browsers
Tracy 2.8 PHP 7.2 – 8.1 Chrome 55+, Firefox 53+, Safari 11+ and iOS Safari 11+
Tracy 2.7 PHP 7.1 – 8.0 Chrome 55+, Firefox 53+, MS Edge 16+, Safari 11+ and iOS Safari 11+
Tracy 2.6 PHP 7.1 – 8.0 Chrome 49+, Firefox 45+, MS Edge 14+, Safari 10+ and iOS Safari 10.2+
Tracy 2.5 PHP 5.4 – 7.4 Chrome 49+, Firefox 45+, MS Edge 12+, Safari 10+ and iOS Safari 10.2+
Tracy 2.4 PHP 5.4 – 7.2 Chrome 29+, Firefox 28+, IE 11+ (except AJAX), MS Edge 12+, Safari 9+ and iOS Safari 9.2+

Usage

Activating Tracy is easy. Simply add these two lines of code, preferably just after library loading (like require 'vendor/autoload.php') and before any output is sent to browser:

use Tracy\Debugger;

Debugger::enable();

The first thing you will notice on the website is a Debugger Bar.

(If you do not see anything, it means that Tracy is running in production mode. For security reasons, Tracy is visible only on localhost. You may force Tracy to run in development mode by passing the Debugger::DEVELOPMENT as the first parameter of enable() method.)

The enable() involves changing the error reporting level to E_ALL.

Debugger Bar

The Debugger Bar is a floating panel. It is displayed in the bottom right corner of a page. You can move it using the mouse. It will remember its position after the page reloading.

Debugger-Bar

You can add other useful panels to the Debugger Bar. You can find interesting ones in addons or you can create your own.

If you do not want to show Debugger Bar, set:

Debugger::$showBar = false;

Visualization of errors and exceptions

Surely, you know how PHP reports errors: there is something like this in the page source code:

<b>Parse error</b>:  syntax error, unexpected '}' in <b>HomepagePresenter.php</b> on line <b>15</b>

or uncaught exception:

<b>Fatal error</b>:  Uncaught Nette\MemberAccessException: Call to undefined method Nette\Application\UI\Form::addTest()? in /sandbox/vendor/nette/utils/src/Utils/ObjectMixin.php:100
Stack trace:
#0 /sandbox/vendor/nette/utils/src/Utils/Object.php(75): Nette\Utils\ObjectMixin::call(Object(Nette\Application\UI\Form), 'addTest', Array)
#1 /sandbox/app/forms/SignFormFactory.php(32): Nette\Object-&gt;__call('addTest', Array)
#2 /sandbox/app/presenters/SignPresenter.php(21): App\Forms\SignFormFactory-&gt;create()
#3 /sandbox/vendor/nette/component-model/src/ComponentModel/Container.php(181): App\Presenters\SignPresenter-&gt;createComponentSignInForm('signInForm')
#4 /sandbox/vendor/nette/component-model/src/ComponentModel/Container.php(139): Nette\ComponentModel\Container-&gt;createComponent('signInForm')
#5 /sandbox/temp/cache/latte/15206b353f351f6bfca2c36cc.php(17): Nette\ComponentModel\Co in <b>/sandbox/vendor/nette/utils/src/Utils/ObjectMixin.php</b> on line <b>100</b><br />

It is not so easy to navigate through this output. If you enable Tracy, both errors and exceptions are displayed in a completely different form:

Uncaught exception rendered by Tracy

The error message literally screams. You can see a part of the source code with the highlighted line where the error occurred. A message clearly explains an error. The entire site is interactive, try it.

And you know what? Fatal errors are captured and displayed in the same way. No need to install any extension (click for live example):

Fatal error rendered by Tracy

Errors like a typo in a variable name or an attempt to open a nonexistent file generate reports of E_NOTICE or E_WARNING level. These can be easily overlooked and/or can be completely hidden in a web page graphic layout. Let Tracy manage them:

Notice rendered by Tracy

Or they may be displayed like errors:

Debugger::$strictMode = true; // display all errors
Debugger::$strictMode = E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED; // all errors except deprecated notices

Notice rendered by Tracy

In order to detect misspellings when assigning to an object, we use trait Nette\SmartObject.

Content Security Policy

If your site uses Content Security Policy, you'll need to add 'nonce-<value>' to script-src and eventually the same nonce to style-src for Tracy to work properly. Some 3rd plugins may require additional directives. Avoid adding 'unsafe-inline' & 'unsafe-eval' in production mode, if you can.

Configuration example for Nette Framework:

http:
	csp:
		script-src: nonce
		style-src: nonce

Faster loading

The basic integration is straightforward, however if you have slow blocking scripts in web page, they can slow the Tracy loading. The solution is to place <?php Tracy\Debugger::renderLoader() ?> into your template before any scripts:

<!DOCTYPE html>
<html>
<head>
	<title>...<title>
	<?php Tracy\Debugger::renderLoader() ?>
	<link rel="stylesheet" href="assets/style.css">
	<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>

AJAX and redirected requests

Tracy is able to show Debug bar and Bluescreens for AJAX and redirected requests. You just have to start session before Tracy:

session_start();
Debugger::enable();

In case you use non-standard session handler, you can start Tracy immediately (in order to handle any errors), then initialize your session handler and then inform Tracy that session is ready to use via dispatch():

Debugger::enable();

// initialize session handler
session_start();

Debugger::dispatch();

Opening files in the editor

When the error page is displayed, you can click on file names and they will open in your editor with the cursor on the corresponding line. Files can also be created (action create file) or bug fixed in them (action fix it). In order to do this, you need to configure the browser and the system.

Production mode and error logging

As you can see, Tracy is quite eloquent. It is appreciated in a development environment, but on a production server, it would cause a disaster. Any debugging information cannot be listed there. Therefore Tracy has an environment autodetection and logging functionality. Instead of showing herself, Tracy stores information into a log file and shows the visitor a user-comprehensible server error message:

Server Error 500

Production output mode suppresses all debugging information which is sent out via dump() or Debugger::fireLog(), and of course all error messages generated by PHP. So, even if you forget dump($obj) in the source code, you do not have to worry about it on your production server. Nothing will be seen.

The output mode is set by the first parameter of Debugger::enable(). You can specify either a constant Debugger::PRODUCTION or Debugger::DEVELOPMENT. Other option is to set it up in a way, that development mode will be on when the application is accessed from a defined IP address with a defined value of tracy-debug cookie. The syntax used to achieve this is cookie-value@ip-address.

If it is not specified, the default value Debugger::DETECT is used. In this case, the system detects a server by IP address. The production mode is chosen if an application is accessed via a public IP address. A local IP address leads to development mode. It is not necessary to set the mode in most cases. The mode is correctly recognized when you are launching the application on your local server or in production.

In the production mode, Tracy automatically captures all errors and exceptions into a text log. Unless you specify otherwise, it will be stored in log/error.log. This error logging is extremely useful. Imagine, that all users of your application are actually betatesters. They are doing cutting-edge work for free when hunting bugs and you would be silly if you threw away their valuable reports to a recycle bin unnoticed.

If you need to log your own messages or caught exceptions, use the method log():

Debugger::log('Unexpected error'); // text message

try {
	criticalOperation();
} catch (Exception $e) {
	Debugger::log($e); // log exception
	// or
	Debugger::log($e, Debugger::ERROR); // also sends an email notification
}

A directory for errors logging can be set by the second parameter of the enable() method:

Debugger::enable(Debugger::DETECT, __DIR__ . '/mylog');

If you want Tracy to log PHP errors like E_NOTICE or E_WARNING with detailed information (HTML report), set Debugger::$logSeverity:

Debugger::$logSeverity = E_NOTICE | E_WARNING;

For a real professional the error log is a crucial source of information and he or she wants to be notified about any new error immediately. Tracy helps him. She is capable of sending an email for every new error record. The variable $email identifies where to send these e-mails:

Debugger::$email = 'admin@example.com';

If you use the Nette Framework, you can set this and others in the configuration file.

To protect your e-mail box from flood, Tracy sends only one message and creates a file email-sent. When a developer receives the e-mail notification, he checks the log, corrects his application and deletes the email-sent monitoring file. This activates the e-mail sending again.

Variable dumping

Every debugging developer is a good friend with the function var_dump, which lists all contents of any variable in detail. Unfortunately, its output is without HTML formatting and outputs the dump into a single line of HTML code, not to mention context escaping. It is necessary to replace the var_dump with a more handy function. That is just what dump() is.

$arr = [10, 20.2, true, null, 'hello'];

dump($arr);
// or Tracy\Debugger::dump($arr);

generates the output:

dump

You can also change the nesting depth by Debugger::$maxDepth and displayed strings length by Debugger::$maxLength. Naturally, lower values accelerate Tracy rendering.

Debugger::$maxDepth = 2; // default: 7
Debugger::$maxLength = 50; // default: 150
Debugger::$dumpTheme = 'dark'; // default: light

The dump() function can display useful location information:

Debugger::$showLocation = true; // shows tooltip with path to the file, where the dump() was called, and tooltips for every dumped objects
Debugger::$showLocation = Tracy\Dumper::LOCATION_CLASS; // shows only tooltips for every dumped object containing path to the file
Debugger::$showLocation = false; // hides all location information

Very handy alternative to dump() is dumpe() (ie. dump and exit) and bdump(). This allows us to dump variables in Debugger Bar. This is useful, because dumps don't mess up the output and we can also add a title to the dump.

bdump([2, 4, 6, 8], 'even numbers up to ten');
bdump([1, 3, 5, 7, 9], 'odd numbers up to ten');

bar dump

Timing

Another useful tool is the debugger stopwatch with a precision of microseconds:

Debugger::timer();

// sweet dreams my cherrie
sleep(2);

$elapsed = Debugger::timer();
// $elapsed = 2

Multiple measurements at once can be achieved by an optional parameter.

Debugger::timer('page-generating');
// some code

Debugger::timer('rss-generating');
// some code

$rssElapsed = Debugger::timer('rss-generating');
$pageElapsed = Debugger::timer('page-generating');
Debugger::timer(); // runs the timer

... // some time-consuming operation

echo Debugger::timer(); // elapsed time in seconds

FireLogger

You cannot always send debugging information to the browser window. This applies to AJAX requests or generating XML files to output. In such cases, you can send the messages by a separate channel into FireLogger. Error, Notice and Warning levels are sent to FireLogger window automatically. It is also possible to log suppressed exceptions in running application when attention to them is important.

How to do it?

  • install extension FireLogger for Chrome
  • turn on Chrome DevTools (using Ctrl-Shift-I key) and open Console

Navigate to the demo page and you will see messages sent from PHP.

Because Tracy\Debugger communicates with FireLogger via HTTP headers, you must call the logging function before the PHP script sends anything to output. It is also possible to enable output buffering and delay the output.

use Tracy\Debugger;

Debugger::fireLog('Hello World'); // send string into FireLogger console

Debugger::fireLog($_SERVER); // or even arrays and objects

Debugger::fireLog(new Exception('Test Exception')); // or exceptions

The result looks like this:

FireLogger

Custom Logger

We can create a custom logger to log errors, uncatched exceptions, and also be called by Tracy\Debugger::log(). Logger implements the interface Tracy\ILogger.

use Tracy\ILogger;

class SlackLogger implements ILogger
{
	public function log($value, $priority = ILogger::INFO)
	{
		// sends a request to Slack
	}
}

And then we activate it:

Tracy\Debugger::setLogger(new SlackLogger);

If we use the full Nette Framework, we can set it in the NEON configuration file:

services:
	tracy.logger: SlackLogger

nginx

If Tracy does not work on nginx, it is probably misconfigured. If there is something like

try_files $uri $uri/ /index.php;

change it to

try_files $uri $uri/ /index.php$is_args$args;

Integrations

This is a list of unofficial integrations to other frameworks and CMS:

... feel free to be famous, create an integration for your favourite platform!

展开阅读全文

代码

评论 (0)

加载中
更多评论
暂无内容
发表了博客
2013/11/05 15:25

iOS7适配之设计篇 - Tracy E

(注:文章简要翻译自 Apple 《iOS 7 UI Transition Guide》 ,由于该文档为开发者预览版,并非最终文档,所以 iOS7 正式上线可能有部分不同) 准备工作 iOS7 带来了很多界面上的改变,如:没有边框(圆角)的按钮,半透明的工具条(UINavigationBar, UIToolBar 等),视图控制器的全屏布局等。使用 Xcode5,你就可以创建 iOS7 工程,并在 iOS7 模拟器中看看 iOS7 的界面。 UIStyle 从 iOS7 系统应用的改变可以看出,iOS7 这次改...

0
0
发表于程序人生专区
2020/04/22 12:29

Tracy Miranda当选CDF理事会新主席

CloudBees开源社区总监Tracy Miranda被选为CDF理事会主席。CloudBees是CDF的主要成员,Tracy在过去的一年里深入参与了CDF的活动,在理事会中服务,帮助制定基金会的9个战略目标,并参与了CDF在全球的活动。 “我很高兴也很荣幸被选为CDF理事会主席。我和所有CDF成员一起,衷心感谢Kim Lewandowski在我们最初的12个月里取得的巨大进步。最近的全球事件强调了持续的软件交付对于每个行业是多么的重要。基金将越来越多地推动这一领...

0
0
发表了博客
2019/08/22 14:15

11-kubernetes RBAC 及授权

[TOC] RBAC 授权插件: Node ABAC RBAC Webhook RBAC 主要的功能是提供基于角色(Role)的访问控制许可(permission) 解释: 让一个用户扮演一个角色(Role),而角色(Role)拥有某些操作的权限,那么这么用户就拥有了该角色的操作权限。 所以说,之后的所有的操作许可,都是直接授权给角色(Role),而不是直接授权给用户。 对象 对象列表 虚拟对象,通常是URL,非对象资源, 对某个对象施加的一种行为,成为 Action。 role 和 cluste...

0
0
发表了博客
2019/05/25 19:51

基于sklearn的分类器实战

已迁移到我新博客,阅读体验更佳基于sklearn的分类器实战 完整代码实现见github:click me 一、实验说明 1.1 任务描述 <div align="center"> <img src='https://raw.githubusercontent.com/tracy-talent/tracy-talent.github.io/hexo/source/images/classifiers/assignment.png'> </div> 1.2 数据说明 一共有十个数据集,数据集中的数据属性有全部是离散型的,有全部是连续型的,也有离散与连续混合型的。通过对各个数据集的浏览...

0
0
发表于开发技能专区
2016/11/05 17:18

python 字典(dict)详解

dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值**(key-value)**存储,具有极快的查找速度。 举个例子,假设要根据同学的名字查找对应的成绩,如果用list实现,需要两个list: names = ['Michael', 'Bob', 'Tracy'] scores = [95, 75, 85] 给定一个名字,要查找对应的成绩,就先要在names中找到对应的位置,再从scores取出对应的成绩,list越长,耗时越长。 如果用dict实现,...

0
0
没有更多内容
加载失败,请刷新页面
点击加载更多
加载中
下一页
暂无内容
0 评论
0 收藏
分享
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部